From bc2d9490b0aad80e1118103c9d28280155c93310 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 12 Nov 2024 20:59:12 +0000 Subject: [PATCH 1/2] docs: Fixed typo in comments in Eventarc protos PiperOrigin-RevId: 695796569 Source-Link: https://github.com/googleapis/googleapis/commit/86ab4967ddb5cd045ad735787cfc8453b335009a Source-Link: https://github.com/googleapis/googleapis-gen/commit/e36e3e26d42034b806f533f04240929510c69c78 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWV2ZW50YXJjLy5Pd2xCb3QueWFtbCIsImgiOiJlMzZlM2UyNmQ0MjAzNGI4MDZmNTMzZjA0MjQwOTI5NTEwYzY5Yzc4In0= --- .../google-cloud-eventarc/v1/.coveragerc | 13 + .../google-cloud-eventarc/v1/.flake8 | 33 + .../google-cloud-eventarc/v1/MANIFEST.in | 2 + .../google-cloud-eventarc/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-cloud-eventarc/v1/docs/conf.py | 376 + .../v1/docs/eventarc_v1/eventarc.rst | 10 + .../v1/docs/eventarc_v1/services_.rst | 6 + .../v1/docs/eventarc_v1/types_.rst | 6 + .../google-cloud-eventarc/v1/docs/index.rst | 7 + .../v1/google/cloud/eventarc/__init__.py | 167 + .../v1/google/cloud/eventarc/gapic_version.py | 16 + .../v1/google/cloud/eventarc/py.typed | 2 + .../v1/google/cloud/eventarc_v1/__init__.py | 168 + .../cloud/eventarc_v1/gapic_metadata.json | 613 + .../google/cloud/eventarc_v1/gapic_version.py | 16 + .../v1/google/cloud/eventarc_v1/py.typed | 2 + .../cloud/eventarc_v1/services/__init__.py | 15 + .../eventarc_v1/services/eventarc/__init__.py | 22 + .../services/eventarc/async_client.py | 5726 +++ .../eventarc_v1/services/eventarc/client.py | 6147 +++ .../eventarc_v1/services/eventarc/pagers.py | 1250 + .../services/eventarc/transports/README.rst | 9 + .../services/eventarc/transports/__init__.py | 38 + .../services/eventarc/transports/base.py | 1013 + .../services/eventarc/transports/grpc.py | 1486 + .../eventarc/transports/grpc_asyncio.py | 1922 + .../services/eventarc/transports/rest.py | 5300 +++ .../services/eventarc/transports/rest_base.py | 1996 + .../cloud/eventarc_v1/types/__init__.py | 182 + .../google/cloud/eventarc_v1/types/channel.py | 168 + .../eventarc_v1/types/channel_connection.py | 92 + .../cloud/eventarc_v1/types/discovery.py | 149 + .../cloud/eventarc_v1/types/enrollment.py | 129 + .../cloud/eventarc_v1/types/eventarc.py | 1745 + .../eventarc_v1/types/google_api_source.py | 130 + .../types/google_channel_config.py | 70 + .../cloud/eventarc_v1/types/logging_config.py | 95 + .../cloud/eventarc_v1/types/message_bus.py | 126 + .../cloud/eventarc_v1/types/network_config.py | 47 + .../cloud/eventarc_v1/types/pipeline.py | 838 + .../google/cloud/eventarc_v1/types/trigger.py | 489 + .../google-cloud-eventarc/v1/mypy.ini | 3 + .../google-cloud-eventarc/v1/noxfile.py | 280 + ...generated_eventarc_create_channel_async.py | 62 + ...ventarc_create_channel_connection_async.py | 62 + ...eventarc_create_channel_connection_sync.py | 62 + ..._generated_eventarc_create_channel_sync.py | 62 + ...erated_eventarc_create_enrollment_async.py | 63 + ...nerated_eventarc_create_enrollment_sync.py | 63 + ...eventarc_create_google_api_source_async.py | 61 + ..._eventarc_create_google_api_source_sync.py | 61 + ...rated_eventarc_create_message_bus_async.py | 57 + ...erated_eventarc_create_message_bus_sync.py | 57 + ...enerated_eventarc_create_pipeline_async.py | 61 + ...generated_eventarc_create_pipeline_sync.py | 61 + ...generated_eventarc_create_trigger_async.py | 65 + ..._generated_eventarc_create_trigger_sync.py | 65 + ...generated_eventarc_delete_channel_async.py | 56 + ...ventarc_delete_channel_connection_async.py | 56 + ...eventarc_delete_channel_connection_sync.py | 56 + ..._generated_eventarc_delete_channel_sync.py | 56 + ...erated_eventarc_delete_enrollment_async.py | 56 + ...nerated_eventarc_delete_enrollment_sync.py | 56 + ...eventarc_delete_google_api_source_async.py | 56 + ..._eventarc_delete_google_api_source_sync.py | 56 + ...rated_eventarc_delete_message_bus_async.py | 56 + ...erated_eventarc_delete_message_bus_sync.py | 56 + ...enerated_eventarc_delete_pipeline_async.py | 56 + ...generated_eventarc_delete_pipeline_sync.py | 56 + ...generated_eventarc_delete_trigger_async.py | 56 + ..._generated_eventarc_delete_trigger_sync.py | 56 + ...v1_generated_eventarc_get_channel_async.py | 52 + ...d_eventarc_get_channel_connection_async.py | 52 + ...ed_eventarc_get_channel_connection_sync.py | 52 + ..._v1_generated_eventarc_get_channel_sync.py | 52 + ...generated_eventarc_get_enrollment_async.py | 52 + ..._generated_eventarc_get_enrollment_sync.py | 52 + ...ed_eventarc_get_google_api_source_async.py | 52 + ...ted_eventarc_get_google_api_source_sync.py | 52 + ...ventarc_get_google_channel_config_async.py | 52 + ...eventarc_get_google_channel_config_sync.py | 52 + ...enerated_eventarc_get_message_bus_async.py | 52 + ...generated_eventarc_get_message_bus_sync.py | 52 + ...1_generated_eventarc_get_pipeline_async.py | 52 + ...v1_generated_eventarc_get_pipeline_sync.py | 52 + ...1_generated_eventarc_get_provider_async.py | 52 + ...v1_generated_eventarc_get_provider_sync.py | 52 + ...v1_generated_eventarc_get_trigger_async.py | 52 + ..._v1_generated_eventarc_get_trigger_sync.py | 52 + ...eventarc_list_channel_connections_async.py | 53 + ..._eventarc_list_channel_connections_sync.py | 53 + ..._generated_eventarc_list_channels_async.py | 53 + ...1_generated_eventarc_list_channels_sync.py | 53 + ...nerated_eventarc_list_enrollments_async.py | 53 + ...enerated_eventarc_list_enrollments_sync.py | 53 + ..._eventarc_list_google_api_sources_async.py | 53 + ...d_eventarc_list_google_api_sources_sync.py | 53 + ...tarc_list_message_bus_enrollments_async.py | 53 + ...ntarc_list_message_bus_enrollments_sync.py | 53 + ...rated_eventarc_list_message_buses_async.py | 53 + ...erated_eventarc_list_message_buses_sync.py | 53 + ...generated_eventarc_list_pipelines_async.py | 53 + ..._generated_eventarc_list_pipelines_sync.py | 53 + ...generated_eventarc_list_providers_async.py | 53 + ..._generated_eventarc_list_providers_sync.py | 53 + ..._generated_eventarc_list_triggers_async.py | 53 + ...1_generated_eventarc_list_triggers_sync.py | 53 + ...generated_eventarc_update_channel_async.py | 55 + ..._generated_eventarc_update_channel_sync.py | 55 + ...erated_eventarc_update_enrollment_async.py | 61 + ...nerated_eventarc_update_enrollment_sync.py | 61 + ...eventarc_update_google_api_source_async.py | 59 + ..._eventarc_update_google_api_source_sync.py | 59 + ...tarc_update_google_channel_config_async.py | 55 + ...ntarc_update_google_channel_config_sync.py | 55 + ...rated_eventarc_update_message_bus_async.py | 55 + ...erated_eventarc_update_message_bus_sync.py | 55 + ...enerated_eventarc_update_pipeline_async.py | 59 + ...generated_eventarc_update_pipeline_sync.py | 59 + ...generated_eventarc_update_trigger_async.py | 55 + ..._generated_eventarc_update_trigger_sync.py | 55 + ...pet_metadata_google.cloud.eventarc.v1.json | 6510 +++ .../v1/scripts/fixup_eventarc_v1_keywords.py | 214 + .../google-cloud-eventarc/v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 7 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/eventarc_v1/__init__.py | 16 + .../unit/gapic/eventarc_v1/test_eventarc.py | 32779 ++++++++++++++++ 137 files changed, 75009 insertions(+) create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py diff --git a/owl-bot-staging/google-cloud-eventarc/v1/.coveragerc b/owl-bot-staging/google-cloud-eventarc/v1/.coveragerc new file mode 100644 index 000000000000..a0c8f972f201 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/eventarc/__init__.py + google/cloud/eventarc/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-eventarc/v1/.flake8 b/owl-bot-staging/google-cloud-eventarc/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in b/owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in new file mode 100644 index 000000000000..a7ef8bafb9c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/eventarc *.py +recursive-include google/cloud/eventarc_v1 *.py diff --git a/owl-bot-staging/google-cloud-eventarc/v1/README.rst b/owl-bot-staging/google-cloud-eventarc/v1/README.rst new file mode 100644 index 000000000000..4c79a1d0f7db --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Eventarc API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Eventarc API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py b/owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py new file mode 100644 index 000000000000..4545505bf3da --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-eventarc documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-eventarc" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-eventarc-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-eventarc.tex", + u"google-cloud-eventarc Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-eventarc", + u"Google Cloud Eventarc Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-eventarc", + u"google-cloud-eventarc Documentation", + author, + "google-cloud-eventarc", + "GAPIC library for Google Cloud Eventarc API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst new file mode 100644 index 000000000000..335577a9f38d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst @@ -0,0 +1,10 @@ +Eventarc +-------------------------- + +.. automodule:: google.cloud.eventarc_v1.services.eventarc + :members: + :inherited-members: + +.. automodule:: google.cloud.eventarc_v1.services.eventarc.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst new file mode 100644 index 000000000000..7ea77f99bdb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Eventarc v1 API +========================================= +.. toctree:: + :maxdepth: 2 + + eventarc diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst new file mode 100644 index 000000000000..5a74926d5bf1 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Eventarc v1 API +====================================== + +.. automodule:: google.cloud.eventarc_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst new file mode 100644 index 000000000000..0a20636626b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + eventarc_v1/services_ + eventarc_v1/types_ diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py new file mode 100644 index 000000000000..15978a3966ed --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.eventarc import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.eventarc_v1.services.eventarc.client import EventarcClient +from google.cloud.eventarc_v1.services.eventarc.async_client import EventarcAsyncClient + +from google.cloud.eventarc_v1.types.channel import Channel +from google.cloud.eventarc_v1.types.channel_connection import ChannelConnection +from google.cloud.eventarc_v1.types.discovery import EventType +from google.cloud.eventarc_v1.types.discovery import FilteringAttribute +from google.cloud.eventarc_v1.types.discovery import Provider +from google.cloud.eventarc_v1.types.enrollment import Enrollment +from google.cloud.eventarc_v1.types.eventarc import CreateChannelConnectionRequest +from google.cloud.eventarc_v1.types.eventarc import CreateChannelRequest +from google.cloud.eventarc_v1.types.eventarc import CreateEnrollmentRequest +from google.cloud.eventarc_v1.types.eventarc import CreateGoogleApiSourceRequest +from google.cloud.eventarc_v1.types.eventarc import CreateMessageBusRequest +from google.cloud.eventarc_v1.types.eventarc import CreatePipelineRequest +from google.cloud.eventarc_v1.types.eventarc import CreateTriggerRequest +from google.cloud.eventarc_v1.types.eventarc import DeleteChannelConnectionRequest +from google.cloud.eventarc_v1.types.eventarc import DeleteChannelRequest +from google.cloud.eventarc_v1.types.eventarc import DeleteEnrollmentRequest +from google.cloud.eventarc_v1.types.eventarc import DeleteGoogleApiSourceRequest +from google.cloud.eventarc_v1.types.eventarc import DeleteMessageBusRequest +from google.cloud.eventarc_v1.types.eventarc import DeletePipelineRequest +from google.cloud.eventarc_v1.types.eventarc import DeleteTriggerRequest +from google.cloud.eventarc_v1.types.eventarc import GetChannelConnectionRequest +from google.cloud.eventarc_v1.types.eventarc import GetChannelRequest +from google.cloud.eventarc_v1.types.eventarc import GetEnrollmentRequest +from google.cloud.eventarc_v1.types.eventarc import GetGoogleApiSourceRequest +from google.cloud.eventarc_v1.types.eventarc import GetGoogleChannelConfigRequest +from google.cloud.eventarc_v1.types.eventarc import GetMessageBusRequest +from google.cloud.eventarc_v1.types.eventarc import GetPipelineRequest +from google.cloud.eventarc_v1.types.eventarc import GetProviderRequest +from google.cloud.eventarc_v1.types.eventarc import GetTriggerRequest +from google.cloud.eventarc_v1.types.eventarc import ListChannelConnectionsRequest +from google.cloud.eventarc_v1.types.eventarc import ListChannelConnectionsResponse +from google.cloud.eventarc_v1.types.eventarc import ListChannelsRequest +from google.cloud.eventarc_v1.types.eventarc import ListChannelsResponse +from google.cloud.eventarc_v1.types.eventarc import ListEnrollmentsRequest +from google.cloud.eventarc_v1.types.eventarc import ListEnrollmentsResponse +from google.cloud.eventarc_v1.types.eventarc import ListGoogleApiSourcesRequest +from google.cloud.eventarc_v1.types.eventarc import ListGoogleApiSourcesResponse +from google.cloud.eventarc_v1.types.eventarc import ListMessageBusEnrollmentsRequest +from google.cloud.eventarc_v1.types.eventarc import ListMessageBusEnrollmentsResponse +from google.cloud.eventarc_v1.types.eventarc import ListMessageBusesRequest +from google.cloud.eventarc_v1.types.eventarc import ListMessageBusesResponse +from google.cloud.eventarc_v1.types.eventarc import ListPipelinesRequest +from google.cloud.eventarc_v1.types.eventarc import ListPipelinesResponse +from google.cloud.eventarc_v1.types.eventarc import ListProvidersRequest +from google.cloud.eventarc_v1.types.eventarc import ListProvidersResponse +from google.cloud.eventarc_v1.types.eventarc import ListTriggersRequest +from google.cloud.eventarc_v1.types.eventarc import ListTriggersResponse +from google.cloud.eventarc_v1.types.eventarc import OperationMetadata +from google.cloud.eventarc_v1.types.eventarc import UpdateChannelRequest +from google.cloud.eventarc_v1.types.eventarc import UpdateEnrollmentRequest +from google.cloud.eventarc_v1.types.eventarc import UpdateGoogleApiSourceRequest +from google.cloud.eventarc_v1.types.eventarc import UpdateGoogleChannelConfigRequest +from google.cloud.eventarc_v1.types.eventarc import UpdateMessageBusRequest +from google.cloud.eventarc_v1.types.eventarc import UpdatePipelineRequest +from google.cloud.eventarc_v1.types.eventarc import UpdateTriggerRequest +from google.cloud.eventarc_v1.types.google_api_source import GoogleApiSource +from google.cloud.eventarc_v1.types.google_channel_config import GoogleChannelConfig +from google.cloud.eventarc_v1.types.logging_config import LoggingConfig +from google.cloud.eventarc_v1.types.message_bus import MessageBus +from google.cloud.eventarc_v1.types.network_config import NetworkConfig +from google.cloud.eventarc_v1.types.pipeline import Pipeline +from google.cloud.eventarc_v1.types.trigger import CloudRun +from google.cloud.eventarc_v1.types.trigger import Destination +from google.cloud.eventarc_v1.types.trigger import EventFilter +from google.cloud.eventarc_v1.types.trigger import GKE +from google.cloud.eventarc_v1.types.trigger import HttpEndpoint +from google.cloud.eventarc_v1.types.trigger import Pubsub +from google.cloud.eventarc_v1.types.trigger import StateCondition +from google.cloud.eventarc_v1.types.trigger import Transport +from google.cloud.eventarc_v1.types.trigger import Trigger + +__all__ = ('EventarcClient', + 'EventarcAsyncClient', + 'Channel', + 'ChannelConnection', + 'EventType', + 'FilteringAttribute', + 'Provider', + 'Enrollment', + 'CreateChannelConnectionRequest', + 'CreateChannelRequest', + 'CreateEnrollmentRequest', + 'CreateGoogleApiSourceRequest', + 'CreateMessageBusRequest', + 'CreatePipelineRequest', + 'CreateTriggerRequest', + 'DeleteChannelConnectionRequest', + 'DeleteChannelRequest', + 'DeleteEnrollmentRequest', + 'DeleteGoogleApiSourceRequest', + 'DeleteMessageBusRequest', + 'DeletePipelineRequest', + 'DeleteTriggerRequest', + 'GetChannelConnectionRequest', + 'GetChannelRequest', + 'GetEnrollmentRequest', + 'GetGoogleApiSourceRequest', + 'GetGoogleChannelConfigRequest', + 'GetMessageBusRequest', + 'GetPipelineRequest', + 'GetProviderRequest', + 'GetTriggerRequest', + 'ListChannelConnectionsRequest', + 'ListChannelConnectionsResponse', + 'ListChannelsRequest', + 'ListChannelsResponse', + 'ListEnrollmentsRequest', + 'ListEnrollmentsResponse', + 'ListGoogleApiSourcesRequest', + 'ListGoogleApiSourcesResponse', + 'ListMessageBusEnrollmentsRequest', + 'ListMessageBusEnrollmentsResponse', + 'ListMessageBusesRequest', + 'ListMessageBusesResponse', + 'ListPipelinesRequest', + 'ListPipelinesResponse', + 'ListProvidersRequest', + 'ListProvidersResponse', + 'ListTriggersRequest', + 'ListTriggersResponse', + 'OperationMetadata', + 'UpdateChannelRequest', + 'UpdateEnrollmentRequest', + 'UpdateGoogleApiSourceRequest', + 'UpdateGoogleChannelConfigRequest', + 'UpdateMessageBusRequest', + 'UpdatePipelineRequest', + 'UpdateTriggerRequest', + 'GoogleApiSource', + 'GoogleChannelConfig', + 'LoggingConfig', + 'MessageBus', + 'NetworkConfig', + 'Pipeline', + 'CloudRun', + 'Destination', + 'EventFilter', + 'GKE', + 'HttpEndpoint', + 'Pubsub', + 'StateCondition', + 'Transport', + 'Trigger', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed new file mode 100644 index 000000000000..ccbcd1359343 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-eventarc package uses inline types. diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py new file mode 100644 index 000000000000..eded7ed9c6fe --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.eventarc_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.eventarc import EventarcClient +from .services.eventarc import EventarcAsyncClient + +from .types.channel import Channel +from .types.channel_connection import ChannelConnection +from .types.discovery import EventType +from .types.discovery import FilteringAttribute +from .types.discovery import Provider +from .types.enrollment import Enrollment +from .types.eventarc import CreateChannelConnectionRequest +from .types.eventarc import CreateChannelRequest +from .types.eventarc import CreateEnrollmentRequest +from .types.eventarc import CreateGoogleApiSourceRequest +from .types.eventarc import CreateMessageBusRequest +from .types.eventarc import CreatePipelineRequest +from .types.eventarc import CreateTriggerRequest +from .types.eventarc import DeleteChannelConnectionRequest +from .types.eventarc import DeleteChannelRequest +from .types.eventarc import DeleteEnrollmentRequest +from .types.eventarc import DeleteGoogleApiSourceRequest +from .types.eventarc import DeleteMessageBusRequest +from .types.eventarc import DeletePipelineRequest +from .types.eventarc import DeleteTriggerRequest +from .types.eventarc import GetChannelConnectionRequest +from .types.eventarc import GetChannelRequest +from .types.eventarc import GetEnrollmentRequest +from .types.eventarc import GetGoogleApiSourceRequest +from .types.eventarc import GetGoogleChannelConfigRequest +from .types.eventarc import GetMessageBusRequest +from .types.eventarc import GetPipelineRequest +from .types.eventarc import GetProviderRequest +from .types.eventarc import GetTriggerRequest +from .types.eventarc import ListChannelConnectionsRequest +from .types.eventarc import ListChannelConnectionsResponse +from .types.eventarc import ListChannelsRequest +from .types.eventarc import ListChannelsResponse +from .types.eventarc import ListEnrollmentsRequest +from .types.eventarc import ListEnrollmentsResponse +from .types.eventarc import ListGoogleApiSourcesRequest +from .types.eventarc import ListGoogleApiSourcesResponse +from .types.eventarc import ListMessageBusEnrollmentsRequest +from .types.eventarc import ListMessageBusEnrollmentsResponse +from .types.eventarc import ListMessageBusesRequest +from .types.eventarc import ListMessageBusesResponse +from .types.eventarc import ListPipelinesRequest +from .types.eventarc import ListPipelinesResponse +from .types.eventarc import ListProvidersRequest +from .types.eventarc import ListProvidersResponse +from .types.eventarc import ListTriggersRequest +from .types.eventarc import ListTriggersResponse +from .types.eventarc import OperationMetadata +from .types.eventarc import UpdateChannelRequest +from .types.eventarc import UpdateEnrollmentRequest +from .types.eventarc import UpdateGoogleApiSourceRequest +from .types.eventarc import UpdateGoogleChannelConfigRequest +from .types.eventarc import UpdateMessageBusRequest +from .types.eventarc import UpdatePipelineRequest +from .types.eventarc import UpdateTriggerRequest +from .types.google_api_source import GoogleApiSource +from .types.google_channel_config import GoogleChannelConfig +from .types.logging_config import LoggingConfig +from .types.message_bus import MessageBus +from .types.network_config import NetworkConfig +from .types.pipeline import Pipeline +from .types.trigger import CloudRun +from .types.trigger import Destination +from .types.trigger import EventFilter +from .types.trigger import GKE +from .types.trigger import HttpEndpoint +from .types.trigger import Pubsub +from .types.trigger import StateCondition +from .types.trigger import Transport +from .types.trigger import Trigger + +__all__ = ( + 'EventarcAsyncClient', +'Channel', +'ChannelConnection', +'CloudRun', +'CreateChannelConnectionRequest', +'CreateChannelRequest', +'CreateEnrollmentRequest', +'CreateGoogleApiSourceRequest', +'CreateMessageBusRequest', +'CreatePipelineRequest', +'CreateTriggerRequest', +'DeleteChannelConnectionRequest', +'DeleteChannelRequest', +'DeleteEnrollmentRequest', +'DeleteGoogleApiSourceRequest', +'DeleteMessageBusRequest', +'DeletePipelineRequest', +'DeleteTriggerRequest', +'Destination', +'Enrollment', +'EventFilter', +'EventType', +'EventarcClient', +'FilteringAttribute', +'GKE', +'GetChannelConnectionRequest', +'GetChannelRequest', +'GetEnrollmentRequest', +'GetGoogleApiSourceRequest', +'GetGoogleChannelConfigRequest', +'GetMessageBusRequest', +'GetPipelineRequest', +'GetProviderRequest', +'GetTriggerRequest', +'GoogleApiSource', +'GoogleChannelConfig', +'HttpEndpoint', +'ListChannelConnectionsRequest', +'ListChannelConnectionsResponse', +'ListChannelsRequest', +'ListChannelsResponse', +'ListEnrollmentsRequest', +'ListEnrollmentsResponse', +'ListGoogleApiSourcesRequest', +'ListGoogleApiSourcesResponse', +'ListMessageBusEnrollmentsRequest', +'ListMessageBusEnrollmentsResponse', +'ListMessageBusesRequest', +'ListMessageBusesResponse', +'ListPipelinesRequest', +'ListPipelinesResponse', +'ListProvidersRequest', +'ListProvidersResponse', +'ListTriggersRequest', +'ListTriggersResponse', +'LoggingConfig', +'MessageBus', +'NetworkConfig', +'OperationMetadata', +'Pipeline', +'Provider', +'Pubsub', +'StateCondition', +'Transport', +'Trigger', +'UpdateChannelRequest', +'UpdateEnrollmentRequest', +'UpdateGoogleApiSourceRequest', +'UpdateGoogleChannelConfigRequest', +'UpdateMessageBusRequest', +'UpdatePipelineRequest', +'UpdateTriggerRequest', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json new file mode 100644 index 000000000000..0f7262654380 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json @@ -0,0 +1,613 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.eventarc_v1", + "protoPackage": "google.cloud.eventarc.v1", + "schema": "1.0", + "services": { + "Eventarc": { + "clients": { + "grpc": { + "libraryClient": "EventarcClient", + "rpcs": { + "CreateChannel": { + "methods": [ + "create_channel" + ] + }, + "CreateChannelConnection": { + "methods": [ + "create_channel_connection" + ] + }, + "CreateEnrollment": { + "methods": [ + "create_enrollment" + ] + }, + "CreateGoogleApiSource": { + "methods": [ + "create_google_api_source" + ] + }, + "CreateMessageBus": { + "methods": [ + "create_message_bus" + ] + }, + "CreatePipeline": { + "methods": [ + "create_pipeline" + ] + }, + "CreateTrigger": { + "methods": [ + "create_trigger" + ] + }, + "DeleteChannel": { + "methods": [ + "delete_channel" + ] + }, + "DeleteChannelConnection": { + "methods": [ + "delete_channel_connection" + ] + }, + "DeleteEnrollment": { + "methods": [ + "delete_enrollment" + ] + }, + "DeleteGoogleApiSource": { + "methods": [ + "delete_google_api_source" + ] + }, + "DeleteMessageBus": { + "methods": [ + "delete_message_bus" + ] + }, + "DeletePipeline": { + "methods": [ + "delete_pipeline" + ] + }, + "DeleteTrigger": { + "methods": [ + "delete_trigger" + ] + }, + "GetChannel": { + "methods": [ + "get_channel" + ] + }, + "GetChannelConnection": { + "methods": [ + "get_channel_connection" + ] + }, + "GetEnrollment": { + "methods": [ + "get_enrollment" + ] + }, + "GetGoogleApiSource": { + "methods": [ + "get_google_api_source" + ] + }, + "GetGoogleChannelConfig": { + "methods": [ + "get_google_channel_config" + ] + }, + "GetMessageBus": { + "methods": [ + "get_message_bus" + ] + }, + "GetPipeline": { + "methods": [ + "get_pipeline" + ] + }, + "GetProvider": { + "methods": [ + "get_provider" + ] + }, + "GetTrigger": { + "methods": [ + "get_trigger" + ] + }, + "ListChannelConnections": { + "methods": [ + "list_channel_connections" + ] + }, + "ListChannels": { + "methods": [ + "list_channels" + ] + }, + "ListEnrollments": { + "methods": [ + "list_enrollments" + ] + }, + "ListGoogleApiSources": { + "methods": [ + "list_google_api_sources" + ] + }, + "ListMessageBusEnrollments": { + "methods": [ + "list_message_bus_enrollments" + ] + }, + "ListMessageBuses": { + "methods": [ + "list_message_buses" + ] + }, + "ListPipelines": { + "methods": [ + "list_pipelines" + ] + }, + "ListProviders": { + "methods": [ + "list_providers" + ] + }, + "ListTriggers": { + "methods": [ + "list_triggers" + ] + }, + "UpdateChannel": { + "methods": [ + "update_channel" + ] + }, + "UpdateEnrollment": { + "methods": [ + "update_enrollment" + ] + }, + "UpdateGoogleApiSource": { + "methods": [ + "update_google_api_source" + ] + }, + "UpdateGoogleChannelConfig": { + "methods": [ + "update_google_channel_config" + ] + }, + "UpdateMessageBus": { + "methods": [ + "update_message_bus" + ] + }, + "UpdatePipeline": { + "methods": [ + "update_pipeline" + ] + }, + "UpdateTrigger": { + "methods": [ + "update_trigger" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EventarcAsyncClient", + "rpcs": { + "CreateChannel": { + "methods": [ + "create_channel" + ] + }, + "CreateChannelConnection": { + "methods": [ + "create_channel_connection" + ] + }, + "CreateEnrollment": { + "methods": [ + "create_enrollment" + ] + }, + "CreateGoogleApiSource": { + "methods": [ + "create_google_api_source" + ] + }, + "CreateMessageBus": { + "methods": [ + "create_message_bus" + ] + }, + "CreatePipeline": { + "methods": [ + "create_pipeline" + ] + }, + "CreateTrigger": { + "methods": [ + "create_trigger" + ] + }, + "DeleteChannel": { + "methods": [ + "delete_channel" + ] + }, + "DeleteChannelConnection": { + "methods": [ + "delete_channel_connection" + ] + }, + "DeleteEnrollment": { + "methods": [ + "delete_enrollment" + ] + }, + "DeleteGoogleApiSource": { + "methods": [ + "delete_google_api_source" + ] + }, + "DeleteMessageBus": { + "methods": [ + "delete_message_bus" + ] + }, + "DeletePipeline": { + "methods": [ + "delete_pipeline" + ] + }, + "DeleteTrigger": { + "methods": [ + "delete_trigger" + ] + }, + "GetChannel": { + "methods": [ + "get_channel" + ] + }, + "GetChannelConnection": { + "methods": [ + "get_channel_connection" + ] + }, + "GetEnrollment": { + "methods": [ + "get_enrollment" + ] + }, + "GetGoogleApiSource": { + "methods": [ + "get_google_api_source" + ] + }, + "GetGoogleChannelConfig": { + "methods": [ + "get_google_channel_config" + ] + }, + "GetMessageBus": { + "methods": [ + "get_message_bus" + ] + }, + "GetPipeline": { + "methods": [ + "get_pipeline" + ] + }, + "GetProvider": { + "methods": [ + "get_provider" + ] + }, + "GetTrigger": { + "methods": [ + "get_trigger" + ] + }, + "ListChannelConnections": { + "methods": [ + "list_channel_connections" + ] + }, + "ListChannels": { + "methods": [ + "list_channels" + ] + }, + "ListEnrollments": { + "methods": [ + "list_enrollments" + ] + }, + "ListGoogleApiSources": { + "methods": [ + "list_google_api_sources" + ] + }, + "ListMessageBusEnrollments": { + "methods": [ + "list_message_bus_enrollments" + ] + }, + "ListMessageBuses": { + "methods": [ + "list_message_buses" + ] + }, + "ListPipelines": { + "methods": [ + "list_pipelines" + ] + }, + "ListProviders": { + "methods": [ + "list_providers" + ] + }, + "ListTriggers": { + "methods": [ + "list_triggers" + ] + }, + "UpdateChannel": { + "methods": [ + "update_channel" + ] + }, + "UpdateEnrollment": { + "methods": [ + "update_enrollment" + ] + }, + "UpdateGoogleApiSource": { + "methods": [ + "update_google_api_source" + ] + }, + "UpdateGoogleChannelConfig": { + "methods": [ + "update_google_channel_config" + ] + }, + "UpdateMessageBus": { + "methods": [ + "update_message_bus" + ] + }, + "UpdatePipeline": { + "methods": [ + "update_pipeline" + ] + }, + "UpdateTrigger": { + "methods": [ + "update_trigger" + ] + } + } + }, + "rest": { + "libraryClient": "EventarcClient", + "rpcs": { + "CreateChannel": { + "methods": [ + "create_channel" + ] + }, + "CreateChannelConnection": { + "methods": [ + "create_channel_connection" + ] + }, + "CreateEnrollment": { + "methods": [ + "create_enrollment" + ] + }, + "CreateGoogleApiSource": { + "methods": [ + "create_google_api_source" + ] + }, + "CreateMessageBus": { + "methods": [ + "create_message_bus" + ] + }, + "CreatePipeline": { + "methods": [ + "create_pipeline" + ] + }, + "CreateTrigger": { + "methods": [ + "create_trigger" + ] + }, + "DeleteChannel": { + "methods": [ + "delete_channel" + ] + }, + "DeleteChannelConnection": { + "methods": [ + "delete_channel_connection" + ] + }, + "DeleteEnrollment": { + "methods": [ + "delete_enrollment" + ] + }, + "DeleteGoogleApiSource": { + "methods": [ + "delete_google_api_source" + ] + }, + "DeleteMessageBus": { + "methods": [ + "delete_message_bus" + ] + }, + "DeletePipeline": { + "methods": [ + "delete_pipeline" + ] + }, + "DeleteTrigger": { + "methods": [ + "delete_trigger" + ] + }, + "GetChannel": { + "methods": [ + "get_channel" + ] + }, + "GetChannelConnection": { + "methods": [ + "get_channel_connection" + ] + }, + "GetEnrollment": { + "methods": [ + "get_enrollment" + ] + }, + "GetGoogleApiSource": { + "methods": [ + "get_google_api_source" + ] + }, + "GetGoogleChannelConfig": { + "methods": [ + "get_google_channel_config" + ] + }, + "GetMessageBus": { + "methods": [ + "get_message_bus" + ] + }, + "GetPipeline": { + "methods": [ + "get_pipeline" + ] + }, + "GetProvider": { + "methods": [ + "get_provider" + ] + }, + "GetTrigger": { + "methods": [ + "get_trigger" + ] + }, + "ListChannelConnections": { + "methods": [ + "list_channel_connections" + ] + }, + "ListChannels": { + "methods": [ + "list_channels" + ] + }, + "ListEnrollments": { + "methods": [ + "list_enrollments" + ] + }, + "ListGoogleApiSources": { + "methods": [ + "list_google_api_sources" + ] + }, + "ListMessageBusEnrollments": { + "methods": [ + "list_message_bus_enrollments" + ] + }, + "ListMessageBuses": { + "methods": [ + "list_message_buses" + ] + }, + "ListPipelines": { + "methods": [ + "list_pipelines" + ] + }, + "ListProviders": { + "methods": [ + "list_providers" + ] + }, + "ListTriggers": { + "methods": [ + "list_triggers" + ] + }, + "UpdateChannel": { + "methods": [ + "update_channel" + ] + }, + "UpdateEnrollment": { + "methods": [ + "update_enrollment" + ] + }, + "UpdateGoogleApiSource": { + "methods": [ + "update_google_api_source" + ] + }, + "UpdateGoogleChannelConfig": { + "methods": [ + "update_google_channel_config" + ] + }, + "UpdateMessageBus": { + "methods": [ + "update_message_bus" + ] + }, + "UpdatePipeline": { + "methods": [ + "update_pipeline" + ] + }, + "UpdateTrigger": { + "methods": [ + "update_trigger" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed new file mode 100644 index 000000000000..ccbcd1359343 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-eventarc package uses inline types. diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py new file mode 100644 index 000000000000..6c6ea026d4bc --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import EventarcClient +from .async_client import EventarcAsyncClient + +__all__ = ( + 'EventarcClient', + 'EventarcAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py new file mode 100644 index 000000000000..e2c8f4067103 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py @@ -0,0 +1,5726 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.eventarc_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +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.eventarc_v1.services.eventarc import pagers +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel as gce_channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline +from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import trigger as gce_trigger +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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EventarcTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EventarcGrpcAsyncIOTransport +from .client import EventarcClient + + +class EventarcAsyncClient: + """Eventarc allows users to subscribe to various events that are + provided by Google Cloud services and forward them to supported + destinations. + """ + + _client: EventarcClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EventarcClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EventarcClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EventarcClient._DEFAULT_UNIVERSE + + channel_path = staticmethod(EventarcClient.channel_path) + parse_channel_path = staticmethod(EventarcClient.parse_channel_path) + channel_connection_path = staticmethod(EventarcClient.channel_connection_path) + parse_channel_connection_path = staticmethod(EventarcClient.parse_channel_connection_path) + cloud_function_path = staticmethod(EventarcClient.cloud_function_path) + parse_cloud_function_path = staticmethod(EventarcClient.parse_cloud_function_path) + crypto_key_path = staticmethod(EventarcClient.crypto_key_path) + parse_crypto_key_path = staticmethod(EventarcClient.parse_crypto_key_path) + enrollment_path = staticmethod(EventarcClient.enrollment_path) + parse_enrollment_path = staticmethod(EventarcClient.parse_enrollment_path) + google_api_source_path = staticmethod(EventarcClient.google_api_source_path) + parse_google_api_source_path = staticmethod(EventarcClient.parse_google_api_source_path) + google_channel_config_path = staticmethod(EventarcClient.google_channel_config_path) + parse_google_channel_config_path = staticmethod(EventarcClient.parse_google_channel_config_path) + message_bus_path = staticmethod(EventarcClient.message_bus_path) + parse_message_bus_path = staticmethod(EventarcClient.parse_message_bus_path) + network_attachment_path = staticmethod(EventarcClient.network_attachment_path) + parse_network_attachment_path = staticmethod(EventarcClient.parse_network_attachment_path) + pipeline_path = staticmethod(EventarcClient.pipeline_path) + parse_pipeline_path = staticmethod(EventarcClient.parse_pipeline_path) + provider_path = staticmethod(EventarcClient.provider_path) + parse_provider_path = staticmethod(EventarcClient.parse_provider_path) + service_path = staticmethod(EventarcClient.service_path) + parse_service_path = staticmethod(EventarcClient.parse_service_path) + service_account_path = staticmethod(EventarcClient.service_account_path) + parse_service_account_path = staticmethod(EventarcClient.parse_service_account_path) + topic_path = staticmethod(EventarcClient.topic_path) + parse_topic_path = staticmethod(EventarcClient.parse_topic_path) + trigger_path = staticmethod(EventarcClient.trigger_path) + parse_trigger_path = staticmethod(EventarcClient.parse_trigger_path) + workflow_path = staticmethod(EventarcClient.workflow_path) + parse_workflow_path = staticmethod(EventarcClient.parse_workflow_path) + common_billing_account_path = staticmethod(EventarcClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EventarcClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EventarcClient.common_folder_path) + parse_common_folder_path = staticmethod(EventarcClient.parse_common_folder_path) + common_organization_path = staticmethod(EventarcClient.common_organization_path) + parse_common_organization_path = staticmethod(EventarcClient.parse_common_organization_path) + common_project_path = staticmethod(EventarcClient.common_project_path) + parse_common_project_path = staticmethod(EventarcClient.parse_common_project_path) + common_location_path = staticmethod(EventarcClient.common_location_path) + parse_common_location_path = staticmethod(EventarcClient.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: + EventarcAsyncClient: The constructed client. + """ + return EventarcClient.from_service_account_info.__func__(EventarcAsyncClient, 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: + EventarcAsyncClient: The constructed client. + """ + return EventarcClient.from_service_account_file.__func__(EventarcAsyncClient, 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 EventarcClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EventarcTransport: + """Returns the transport used by the client instance. + + Returns: + EventarcTransport: 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 = EventarcClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EventarcTransport, Callable[..., EventarcTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the eventarc 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,EventarcTransport,Callable[..., EventarcTransport]]]): + 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 EventarcTransport 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 = EventarcClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_trigger(self, + request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trigger.Trigger: + r"""Get a single trigger. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetTriggerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_trigger(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetTriggerRequest, dict]]): + The request object. The request message for the + GetTrigger method. + name (:class:`str`): + Required. The name of the trigger 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Trigger: + A representation of the trigger + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetTriggerRequest): + request = eventarc.GetTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_trigger] + + # Certain 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_triggers(self, + request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTriggersAsyncPager: + r"""List triggers. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_triggers(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListTriggersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_triggers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListTriggersRequest, dict]]): + The request object. The request message for the + ListTriggers method. + parent (:class:`str`): + Required. The parent collection to + list triggers on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersAsyncPager: + The response message for the ListTriggers method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListTriggersRequest): + request = eventarc.ListTriggersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_triggers] + + # Certain 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.ListTriggersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_trigger(self, + request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, + *, + parent: Optional[str] = None, + trigger: Optional[gce_trigger.Trigger] = None, + trigger_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new trigger in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + trigger = eventarc_v1.Trigger() + trigger.name = "name_value" + trigger.event_filters.attribute = "attribute_value" + trigger.event_filters.value = "value_value" + trigger.destination.cloud_run.service = "service_value" + trigger.destination.cloud_run.region = "region_value" + + request = eventarc_v1.CreateTriggerRequest( + parent="parent_value", + trigger=trigger, + trigger_id="trigger_id_value", + ) + + # Make the request + operation = client.create_trigger(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateTriggerRequest, dict]]): + The request object. The request message for the + CreateTrigger method. + parent (:class:`str`): + Required. The parent collection in + which to add this trigger. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger (:class:`google.cloud.eventarc_v1.types.Trigger`): + Required. The trigger to create. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (:class:`str`): + Required. The user-provided ID to be + assigned to the trigger. + + This corresponds to the ``trigger_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Trigger` A + representation of the trigger resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, trigger, trigger_id]) + if request is 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, eventarc.CreateTriggerRequest): + request = eventarc.CreateTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if trigger is not None: + request.trigger = trigger + if trigger_id is not None: + request.trigger_id = trigger_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_trigger] + + # Certain 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, + gce_trigger.Trigger, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_trigger(self, + request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, + *, + trigger: Optional[gce_trigger.Trigger] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single trigger. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateTriggerRequest( + ) + + # Make the request + operation = client.update_trigger(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateTriggerRequest, dict]]): + The request object. The request message for the + UpdateTrigger method. + trigger (:class:`google.cloud.eventarc_v1.types.Trigger`): + The trigger to be updated. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update + all fields, provide a field mask of "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + allow_missing (:class:`bool`): + If set to true, and the trigger is not found, a new + trigger will be created. In this situation, + ``update_mask`` is ignored. + + This corresponds to the ``allow_missing`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Trigger` A + representation of the trigger resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([trigger, update_mask, allow_missing]) + if request is 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, eventarc.UpdateTriggerRequest): + request = eventarc.UpdateTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if trigger is not None: + request.trigger = trigger + if update_mask is not None: + request.update_mask = update_mask + if allow_missing is not None: + request.allow_missing = allow_missing + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_trigger] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("trigger.name", request.trigger.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, + gce_trigger.Trigger, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_trigger(self, + request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single trigger. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteTriggerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_trigger(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteTriggerRequest, dict]]): + The request object. The request message for the + DeleteTrigger method. + name (:class:`str`): + Required. The name of the trigger to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + allow_missing (:class:`bool`): + If set to true, and the trigger is + not found, the request will succeed but + no action will be taken on the server. + + This corresponds to the ``allow_missing`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Trigger` A + representation of the trigger resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, allow_missing]) + if request is 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, eventarc.DeleteTriggerRequest): + request = eventarc.DeleteTriggerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if allow_missing is not None: + request.allow_missing = allow_missing + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_trigger] + + # Certain 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, + trigger.Trigger, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_channel(self, + request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> channel.Channel: + r"""Get a single Channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelRequest( + name="name_value", + ) + + # Make the request + response = await client.get_channel(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetChannelRequest, dict]]): + The request object. The request message for the + GetChannel method. + name (:class:`str`): + Required. The name of the channel 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Channel: + A representation of the Channel + resource. A Channel is a resource on + which event providers publish their + events. The published events are + delivered through the transport + associated with the channel. Note that a + channel is associated with exactly one + event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetChannelRequest): + request = eventarc.GetChannelRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_channel] + + # Certain 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_channels(self, + request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChannelsAsyncPager: + r"""List channels. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_channels(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channels(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListChannelsRequest, dict]]): + The request object. The request message for the + ListChannels method. + parent (:class:`str`): + Required. The parent collection to + list channels on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsAsyncPager: + The response message for the ListChannels method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListChannelsRequest): + request = eventarc.ListChannelsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_channels] + + # Certain 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.ListChannelsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_channel(self, + request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[gce_channel.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new channel in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + channel = eventarc_v1.Channel() + channel.pubsub_topic = "pubsub_topic_value" + channel.name = "name_value" + + request = eventarc_v1.CreateChannelRequest( + parent="parent_value", + channel=channel, + channel_id="channel_id_value", + ) + + # Make the request + operation = client.create_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateChannelRequest, dict]]): + The request object. The request message for the + CreateChannel method. + parent (:class:`str`): + Required. The parent collection in + which to add this channel. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel (:class:`google.cloud.eventarc_v1.types.Channel`): + Required. The channel to create. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_id (:class:`str`): + Required. The user-provided ID to be + assigned to the channel. + + This corresponds to the ``channel_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. + A Channel is a resource on which event providers + publish their events. The published events are + delivered through the transport associated with the + channel. Note that a channel is associated with + exactly one event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel, channel_id]) + if request is 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, eventarc.CreateChannelRequest): + request = eventarc.CreateChannelRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel is not None: + request.channel = channel + if channel_id is not None: + request.channel_id = channel_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_channel_] + + # Certain 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, + gce_channel.Channel, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_channel(self, + request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, + *, + channel: Optional[gce_channel.Channel] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateChannelRequest( + ) + + # Make the request + operation = client.update_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateChannelRequest, dict]]): + The request object. The request message for the + UpdateChannel method. + channel (:class:`google.cloud.eventarc_v1.types.Channel`): + The channel to be updated. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update + all fields, provide a field mask of "*". + + This 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. + A Channel is a resource on which event providers + publish their events. The published events are + delivered through the transport associated with the + channel. Note that a channel is associated with + exactly one event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([channel, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.UpdateChannelRequest): + request = eventarc.UpdateChannelRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if channel is not None: + request.channel = channel + 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_channel] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("channel.name", request.channel.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, + gce_channel.Channel, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_channel(self, + request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteChannelRequest, dict]]): + The request object. The request message for the + DeleteChannel method. + name (:class:`str`): + Required. The name of the channel to + be deleted. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. + A Channel is a resource on which event providers + publish their events. The published events are + delivered through the transport associated with the + channel. Note that a channel is associated with + exactly one event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.DeleteChannelRequest): + request = eventarc.DeleteChannelRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_channel] + + # Certain 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, + channel.Channel, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_provider(self, + request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> discovery.Provider: + r"""Get a single Provider. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_provider(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetProviderRequest( + name="name_value", + ) + + # Make the request + response = await client.get_provider(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetProviderRequest, dict]]): + The request object. The request message for the + GetProvider method. + name (:class:`str`): + Required. The name of the provider 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Provider: + A representation of the Provider + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetProviderRequest): + request = eventarc.GetProviderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_provider] + + # Certain 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_providers(self, + request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProvidersAsyncPager: + r"""List providers. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_providers(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_providers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListProvidersRequest, dict]]): + The request object. The request message for the + ListProviders method. + parent (:class:`str`): + Required. The parent of the provider + to get. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersAsyncPager: + The response message for the ListProviders method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListProvidersRequest): + request = eventarc.ListProvidersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_providers] + + # Certain 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.ListProvidersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_channel_connection(self, + request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> channel_connection.ChannelConnection: + r"""Get a single ChannelConnection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_channel_connection(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelConnectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_channel_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetChannelConnectionRequest, dict]]): + The request object. The request message for the + GetChannelConnection method. + name (:class:`str`): + Required. The name of the channel + connection 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.ChannelConnection: + A representation of the + ChannelConnection resource. A + ChannelConnection is a resource which + event providers create during the + activation process to establish a + connection between the provider and the + subscriber channel. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetChannelConnectionRequest): + request = eventarc.GetChannelConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_channel_connection] + + # Certain 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_channel_connections(self, + request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChannelConnectionsAsyncPager: + r"""List channel connections. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_channel_connections(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channel_connections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListChannelConnectionsRequest, dict]]): + The request object. The request message for the + ListChannelConnections method. + parent (:class:`str`): + Required. The parent collection from + which to list channel connections. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsAsyncPager: + The response message for the ListChannelConnections + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListChannelConnectionsRequest): + request = eventarc.ListChannelConnectionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_channel_connections] + + # Certain 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.ListChannelConnectionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_channel_connection(self, + request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, + channel_connection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new ChannelConnection in a particular + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_channel_connection(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + channel_connection = eventarc_v1.ChannelConnection() + channel_connection.name = "name_value" + channel_connection.channel = "channel_value" + + request = eventarc_v1.CreateChannelConnectionRequest( + parent="parent_value", + channel_connection=channel_connection, + channel_connection_id="channel_connection_id_value", + ) + + # Make the request + operation = client.create_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateChannelConnectionRequest, dict]]): + The request object. The request message for the + CreateChannelConnection method. + parent (:class:`str`): + Required. The parent collection in + which to add this channel connection. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_connection (:class:`google.cloud.eventarc_v1.types.ChannelConnection`): + Required. Channel connection to + create. + + This corresponds to the ``channel_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_connection_id (:class:`str`): + Required. The user-provided ID to be + assigned to the channel connection. + + This corresponds to the ``channel_connection_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. + A ChannelConnection is a resource which event + providers create during the activation process to + establish a connection between the provider and the + subscriber channel. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel_connection, channel_connection_id]) + if request is 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, eventarc.CreateChannelConnectionRequest): + request = eventarc.CreateChannelConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel_connection is not None: + request.channel_connection = channel_connection + if channel_connection_id is not None: + request.channel_connection_id = channel_connection_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_channel_connection] + + # Certain 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, + gce_channel_connection.ChannelConnection, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_channel_connection(self, + request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single ChannelConnection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_channel_connection(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelConnectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest, dict]]): + The request object. The request message for the + DeleteChannelConnection method. + name (:class:`str`): + Required. The name of the channel + connection 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. + A ChannelConnection is a resource which event + providers create during the activation process to + establish a connection between the provider and the + subscriber channel. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.DeleteChannelConnectionRequest): + request = eventarc.DeleteChannelConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_channel_connection] + + # Certain 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, + channel_connection.ChannelConnection, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_google_channel_config(self, + request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_channel_config.GoogleChannelConfig: + r"""Get a GoogleChannelConfig + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleChannelConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_google_channel_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest, dict]]): + The request object. The request message for the + GetGoogleChannelConfig method. + name (:class:`str`): + Required. The name of the config 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetGoogleChannelConfigRequest): + request = eventarc.GetGoogleChannelConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_google_channel_config] + + # Certain 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_google_channel_config(self, + request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, + *, + google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: + r"""Update a single GoogleChannelConfig + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_channel_config = eventarc_v1.GoogleChannelConfig() + google_channel_config.name = "name_value" + + request = eventarc_v1.UpdateGoogleChannelConfigRequest( + google_channel_config=google_channel_config, + ) + + # Make the request + response = await client.update_google_channel_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest, dict]]): + The request object. The request message for the + UpdateGoogleChannelConfig method. + google_channel_config (:class:`google.cloud.eventarc_v1.types.GoogleChannelConfig`): + Required. The config to be updated. + This corresponds to the ``google_channel_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update + all fields, provide a field mask of "*". + + This 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_channel_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.UpdateGoogleChannelConfigRequest): + request = eventarc.UpdateGoogleChannelConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_channel_config is not None: + request.google_channel_config = google_channel_config + 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_google_channel_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_channel_config.name", request.google_channel_config.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_message_bus(self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message_bus.MessageBus: + r"""Get a single MessageBus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message_bus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetMessageBusRequest, dict]]): + The request object. The request message for the + GetMessageBus method. + name (:class:`str`): + Required. The name of the message bus + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.MessageBus: + MessageBus for the messages flowing + through the system. The admin has + visibility and control over the messages + being published and consumed and can + restrict publishers and subscribers to + only a subset of data available in the + system by defining authorization + policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetMessageBusRequest): + request = eventarc.GetMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_message_bus] + + # Certain 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_message_buses(self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusesAsyncPager: + r"""List message buses. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListMessageBusesRequest, dict]]): + The request object. The request message for the + ListMessageBuses method. + parent (:class:`str`): + Required. The parent collection to + list triggers on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesAsyncPager: + The response message for the ListMessageBuses method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListMessageBusesRequest): + request = eventarc.ListMessageBusesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message_buses] + + # Certain 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.ListMessageBusesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_message_bus_enrollments(self, + request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusEnrollmentsAsyncPager: + r"""List message bus enrollments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest, dict]]): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + parent (:class:`str`): + Required. The parent message bus to + list enrollments on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsAsyncPager: + The response message for the ListMessageBusEnrollments + method.\` + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListMessageBusEnrollmentsRequest): + request = eventarc.ListMessageBusEnrollmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message_bus_enrollments] + + # Certain 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.ListMessageBusEnrollmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_message_bus(self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new MessageBus in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateMessageBusRequest, dict]]): + The request object. The request message for the + CreateMessageBus method. + parent (:class:`str`): + Required. The parent collection in + which to add this message bus. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus (:class:`google.cloud.eventarc_v1.types.MessageBus`): + Required. The message bus to create. + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus_id (:class:`str`): + Required. The user-provided ID to be assigned to the + MessageBus. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + + This corresponds to the ``message_bus_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, message_bus, message_bus_id]) + if request is 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, eventarc.CreateMessageBusRequest): + request = eventarc.CreateMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message_bus is not None: + request.message_bus = message_bus + if message_bus_id is not None: + request.message_bus_id = message_bus_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_message_bus] + + # Certain 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, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_message_bus(self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single message bus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateMessageBusRequest, dict]]): + The request object. The request message for the + UpdateMessageBus method. + message_bus (:class:`google.cloud.eventarc_v1.types.MessageBus`): + Required. The MessageBus to be + updated. + + This corresponds to the ``message_bus`` 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 fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([message_bus, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.UpdateMessageBusRequest): + request = eventarc.UpdateMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message_bus is not None: + request.message_bus = message_bus + 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_message_bus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("message_bus.name", request.message_bus.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, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_message_bus(self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single message bus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteMessageBusRequest, dict]]): + The request object. The request message for the + DeleteMessageBus method. + name (:class:`str`): + Required. The name of the MessageBus + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeleteMessageBusRequest): + request = eventarc.DeleteMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_message_bus] + + # Certain 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, + message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_enrollment(self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> enrollment.Enrollment: + r"""Get a single Enrollment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_enrollment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetEnrollmentRequest, dict]]): + The request object. The request message for the + GetEnrollment method. + name (:class:`str`): + Required. The name of the Enrollment + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Enrollment: + An enrollment represents a + subscription for messages on a + particular message bus. It defines a + matching criteria for messages on the + bus and the subscriber endpoint where + matched messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetEnrollmentRequest): + request = eventarc.GetEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_enrollment] + + # Certain 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_enrollments(self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnrollmentsAsyncPager: + r"""List Enrollments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListEnrollmentsRequest, dict]]): + The request object. The request message for the + ListEnrollments method. + parent (:class:`str`): + Required. The parent collection to + list triggers on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsAsyncPager: + The response message for the ListEnrollments method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListEnrollmentsRequest): + request = eventarc.ListEnrollmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_enrollments] + + # Certain 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.ListEnrollmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_enrollment(self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new Enrollment in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateEnrollmentRequest, dict]]): + The request object. The request message for the + CreateEnrollment method. + parent (:class:`str`): + Required. The parent collection in + which to add this enrollment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment (:class:`google.cloud.eventarc_v1.types.Enrollment`): + Required. The enrollment to create. + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment_id (:class:`str`): + Required. The user-provided ID to be assigned to the + Enrollment. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``enrollment_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, enrollment, enrollment_id]) + if request is 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, eventarc.CreateEnrollmentRequest): + request = eventarc.CreateEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if enrollment is not None: + request.enrollment = enrollment + if enrollment_id is not None: + request.enrollment_id = enrollment_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_enrollment] + + # Certain 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, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_enrollment(self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single Enrollment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateEnrollmentRequest, dict]]): + The request object. The request message for the + UpdateEnrollment method. + enrollment (:class:`google.cloud.eventarc_v1.types.Enrollment`): + Required. The Enrollment to be + updated. + + This corresponds to the ``enrollment`` 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 fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([enrollment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.UpdateEnrollmentRequest): + request = eventarc.UpdateEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enrollment is not None: + request.enrollment = enrollment + 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_enrollment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("enrollment.name", request.enrollment.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, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_enrollment(self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single Enrollment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteEnrollmentRequest, dict]]): + The request object. The request message for the + DeleteEnrollment method. + name (:class:`str`): + Required. The name of the Enrollment + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the Enrollment + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeleteEnrollmentRequest): + request = eventarc.DeleteEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_enrollment] + + # Certain 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, + enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_pipeline(self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pipeline.Pipeline: + r"""Get a single Pipeline. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_pipeline(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetPipelineRequest, dict]]): + The request object. The request message for the + GetPipeline method. + name (:class:`str`): + Required. The name of the pipeline 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Pipeline: + A representation of the Pipeline + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetPipelineRequest): + request = eventarc.GetPipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_pipeline] + + # Certain 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_pipelines(self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPipelinesAsyncPager: + r"""List pipelines. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListPipelinesRequest, dict]]): + The request object. The request message for the + ListPipelines method. + parent (:class:`str`): + Required. The parent collection to + list pipelines on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesAsyncPager: + The response message for the + ListPipelines method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListPipelinesRequest): + request = eventarc.ListPipelinesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_pipelines] + + # Certain 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.ListPipelinesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_pipeline(self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new Pipeline in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreatePipelineRequest, dict]]): + The request object. The request message for the + CreatePipeline method. + parent (:class:`str`): + Required. The parent collection in + which to add this pipeline. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline (:class:`google.cloud.eventarc_v1.types.Pipeline`): + Required. The pipeline to create. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline_id (:class:`str`): + Required. The user-provided ID to be + assigned to the Pipeline. + + This corresponds to the ``pipeline_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, pipeline, pipeline_id]) + if request is 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, eventarc.CreatePipelineRequest): + request = eventarc.CreatePipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if pipeline is not None: + request.pipeline = pipeline + if pipeline_id is not None: + request.pipeline_id = pipeline_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_pipeline] + + # Certain 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, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_pipeline(self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single pipeline. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdatePipelineRequest, dict]]): + The request object. The request message for the + UpdatePipeline method. + pipeline (:class:`google.cloud.eventarc_v1.types.Pipeline`): + Required. The Pipeline to be updated. + This corresponds to the ``pipeline`` 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 fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([pipeline, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.UpdatePipelineRequest): + request = eventarc.UpdatePipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if pipeline is not None: + request.pipeline = pipeline + 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_pipeline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("pipeline.name", request.pipeline.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, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_pipeline(self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single pipeline. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeletePipelineRequest, dict]]): + The request object. The request message for the + DeletePipeline method. + name (:class:`str`): + Required. The name of the Pipeline to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the Pipeline + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeletePipelineRequest): + request = eventarc.DeletePipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_pipeline] + + # Certain 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, + pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_google_api_source(self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_api_source.GoogleApiSource: + r"""Get a single GoogleApiSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_google_api_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest, dict]]): + The request object. The request message for the + GetGoogleApiSource method. + name (:class:`str`): + Required. The name of the google api + source 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleApiSource: + A GoogleApiSource represents a + subscription of 1P events from a + MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetGoogleApiSourceRequest): + request = eventarc.GetGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_google_api_source] + + # Certain 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_google_api_sources(self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGoogleApiSourcesAsyncPager: + r"""List GoogleApiSources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest, dict]]): + The request object. The request message for the + ListGoogleApiSources method. + parent (:class:`str`): + Required. The parent collection to + list GoogleApiSources on. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesAsyncPager: + The response message for the ListGoogleApiSources + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.ListGoogleApiSourcesRequest): + request = eventarc.ListGoogleApiSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_google_api_sources] + + # Certain 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.ListGoogleApiSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_google_api_source(self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new GoogleApiSource in a particular project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest, dict]]): + The request object. The request message for the + CreateGoogleApiSource method. + parent (:class:`str`): + Required. The parent collection in + which to add this google api source. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source (:class:`google.cloud.eventarc_v1.types.GoogleApiSource`): + Required. The google api source to + create. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source_id (:class:`str`): + Required. The user-provided ID to be assigned to the + GoogleApiSource. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``google_api_source_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, google_api_source, google_api_source_id]) + if request is 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, eventarc.CreateGoogleApiSourceRequest): + request = eventarc.CreateGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_api_source is not None: + request.google_api_source = google_api_source + if google_api_source_id is not None: + request.google_api_source_id = google_api_source_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_google_api_source] + + # Certain 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, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_google_api_source(self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single GoogleApiSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest, dict]]): + The request object. The request message for the + UpdateGoogleApiSource method. + google_api_source (:class:`google.cloud.eventarc_v1.types.GoogleApiSource`): + Required. The GoogleApiSource to be + updated. + + This corresponds to the ``google_api_source`` 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 fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_api_source, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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, eventarc.UpdateGoogleApiSourceRequest): + request = eventarc.UpdateGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_api_source is not None: + request.google_api_source = google_api_source + 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_google_api_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_api_source.name", request.google_api_source.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, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_google_api_source(self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single GoogleApiSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest, dict]]): + The request object. The request message for the + DeleteGoogleApiSource method. + name (:class:`str`): + Required. The name of the + GoogleApiSource to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeleteGoogleApiSourceRequest): + request = eventarc.DeleteGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_google_api_source] + + # Certain 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, + google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.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 cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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) -> "EventarcAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EventarcAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py new file mode 100644 index 000000000000..3149b461d564 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py @@ -0,0 +1,6147 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.eventarc_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.eventarc_v1.services.eventarc import pagers +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel as gce_channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline +from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import trigger as gce_trigger +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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EventarcTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EventarcGrpcTransport +from .transports.grpc_asyncio import EventarcGrpcAsyncIOTransport +from .transports.rest import EventarcRestTransport + + +class EventarcClientMeta(type): + """Metaclass for the Eventarc 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[EventarcTransport]] + _transport_registry["grpc"] = EventarcGrpcTransport + _transport_registry["grpc_asyncio"] = EventarcGrpcAsyncIOTransport + _transport_registry["rest"] = EventarcRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EventarcTransport]: + """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 EventarcClient(metaclass=EventarcClientMeta): + """Eventarc allows users to subscribe to various events that are + provided by Google Cloud services and forward them to supported + destinations. + """ + + @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 = "eventarc.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "eventarc.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EventarcClient: 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: + EventarcClient: 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) -> EventarcTransport: + """Returns the transport used by the client instance. + + Returns: + EventarcTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def channel_path(project: str,location: str,channel: str,) -> str: + """Returns a fully-qualified channel string.""" + return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + + @staticmethod + def parse_channel_path(path: str) -> Dict[str,str]: + """Parses a channel path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def channel_connection_path(project: str,location: str,channel_connection: str,) -> str: + """Returns a fully-qualified channel_connection string.""" + return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) + + @staticmethod + def parse_channel_connection_path(path: str) -> Dict[str,str]: + """Parses a channel_connection path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cloud_function_path(project: str,location: str,function: str,) -> str: + """Returns a fully-qualified cloud_function string.""" + return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + + @staticmethod + def parse_cloud_function_path(path: str) -> Dict[str,str]: + """Parses a cloud_function path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 enrollment_path(project: str,location: str,enrollment: str,) -> str: + """Returns a fully-qualified enrollment string.""" + return "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) + + @staticmethod + def parse_enrollment_path(path: str) -> Dict[str,str]: + """Parses a enrollment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def google_api_source_path(project: str,location: str,google_api_source: str,) -> str: + """Returns a fully-qualified google_api_source string.""" + return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) + + @staticmethod + def parse_google_api_source_path(path: str) -> Dict[str,str]: + """Parses a google_api_source path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def google_channel_config_path(project: str,location: str,) -> str: + """Returns a fully-qualified google_channel_config string.""" + return "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) + + @staticmethod + def parse_google_channel_config_path(path: str) -> Dict[str,str]: + """Parses a google_channel_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_bus_path(project: str,location: str,message_bus: str,) -> str: + """Returns a fully-qualified message_bus string.""" + return "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) + + @staticmethod + def parse_message_bus_path(path: str) -> Dict[str,str]: + """Parses a message_bus path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_attachment_path(project: str,region: str,networkattachment: str,) -> str: + """Returns a fully-qualified network_attachment string.""" + return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) + + @staticmethod + def parse_network_attachment_path(path: str) -> Dict[str,str]: + """Parses a network_attachment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def pipeline_path(project: str,location: str,pipeline: str,) -> str: + """Returns a fully-qualified pipeline string.""" + return "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) + + @staticmethod + def parse_pipeline_path(path: str) -> Dict[str,str]: + """Parses a pipeline path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def provider_path(project: str,location: str,provider: str,) -> str: + """Returns a fully-qualified provider string.""" + return "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) + + @staticmethod + def parse_provider_path(path: str) -> Dict[str,str]: + """Parses a provider path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path() -> str: + """Returns a fully-qualified service string.""" + return "*".format() + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^.*$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_account_path(project: str,service_account: str,) -> str: + """Returns a fully-qualified service_account string.""" + return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + + @staticmethod + def parse_service_account_path(path: str) -> Dict[str,str]: + """Parses a service_account path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def trigger_path(project: str,location: str,trigger: str,) -> str: + """Returns a fully-qualified trigger string.""" + return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + + @staticmethod + def parse_trigger_path(path: str) -> Dict[str,str]: + """Parses a trigger path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workflow_path(project: str,location: str,workflow: str,) -> str: + """Returns a fully-qualified workflow string.""" + return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + + @staticmethod + def parse_workflow_path(path: str) -> Dict[str,str]: + """Parses a workflow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", 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 = EventarcClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EventarcClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EventarcClient._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 = EventarcClient._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 + + @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, EventarcTransport, Callable[..., EventarcTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the eventarc client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. 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,EventarcTransport,Callable[..., EventarcTransport]]]): + 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 EventarcTransport 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 = EventarcClient._read_environment_variables() + self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EventarcClient._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 + + 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, EventarcTransport) + if transport_provided: + # transport is a EventarcTransport 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(EventarcTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EventarcClient._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[EventarcTransport], Callable[..., EventarcTransport]] = ( + EventarcClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EventarcTransport], 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, + ) + + def get_trigger(self, + request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trigger.Trigger: + r"""Get a single trigger. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetTriggerRequest( + name="name_value", + ) + + # Make the request + response = client.get_trigger(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetTriggerRequest, dict]): + The request object. The request message for the + GetTrigger method. + name (str): + Required. The name of the trigger 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Trigger: + A representation of the trigger + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetTriggerRequest): + request = eventarc.GetTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_trigger] + + # Certain 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_triggers(self, + request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTriggersPager: + r"""List triggers. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_triggers(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListTriggersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_triggers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListTriggersRequest, dict]): + The request object. The request message for the + ListTriggers method. + parent (str): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersPager: + The response message for the ListTriggers method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListTriggersRequest): + request = eventarc.ListTriggersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_triggers] + + # Certain 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.ListTriggersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_trigger(self, + request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, + *, + parent: Optional[str] = None, + trigger: Optional[gce_trigger.Trigger] = None, + trigger_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new trigger in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + trigger = eventarc_v1.Trigger() + trigger.name = "name_value" + trigger.event_filters.attribute = "attribute_value" + trigger.event_filters.value = "value_value" + trigger.destination.cloud_run.service = "service_value" + trigger.destination.cloud_run.region = "region_value" + + request = eventarc_v1.CreateTriggerRequest( + parent="parent_value", + trigger=trigger, + trigger_id="trigger_id_value", + ) + + # Make the request + operation = client.create_trigger(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateTriggerRequest, dict]): + The request object. The request message for the + CreateTrigger method. + parent (str): + Required. The parent collection in + which to add this trigger. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger (google.cloud.eventarc_v1.types.Trigger): + Required. The trigger to create. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trigger_id (str): + Required. The user-provided ID to be + assigned to the trigger. + + This corresponds to the ``trigger_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Trigger` A + representation of the trigger resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, trigger, trigger_id]) + if request is 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, eventarc.CreateTriggerRequest): + request = eventarc.CreateTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if trigger is not None: + request.trigger = trigger + if trigger_id is not None: + request.trigger_id = trigger_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_trigger] + + # Certain 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, + gce_trigger.Trigger, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_trigger(self, + request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, + *, + trigger: Optional[gce_trigger.Trigger] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single trigger. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateTriggerRequest( + ) + + # Make the request + operation = client.update_trigger(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateTriggerRequest, dict]): + The request object. The request message for the + UpdateTrigger method. + trigger (google.cloud.eventarc_v1.types.Trigger): + The trigger to be updated. + This corresponds to the ``trigger`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update + all fields, provide a field mask of "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + allow_missing (bool): + If set to true, and the trigger is not found, a new + trigger will be created. In this situation, + ``update_mask`` is ignored. + + This corresponds to the ``allow_missing`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Trigger` A + representation of the trigger resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([trigger, update_mask, allow_missing]) + if request is 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, eventarc.UpdateTriggerRequest): + request = eventarc.UpdateTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if trigger is not None: + request.trigger = trigger + if update_mask is not None: + request.update_mask = update_mask + if allow_missing is not None: + request.allow_missing = allow_missing + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_trigger] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("trigger.name", request.trigger.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, + gce_trigger.Trigger, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_trigger(self, + request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single trigger. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteTriggerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_trigger(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteTriggerRequest, dict]): + The request object. The request message for the + DeleteTrigger method. + name (str): + Required. The name of the trigger to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + allow_missing (bool): + If set to true, and the trigger is + not found, the request will succeed but + no action will be taken on the server. + + This corresponds to the ``allow_missing`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Trigger` A + representation of the trigger resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, allow_missing]) + if request is 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, eventarc.DeleteTriggerRequest): + request = eventarc.DeleteTriggerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if allow_missing is not None: + request.allow_missing = allow_missing + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_trigger] + + # Certain 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, + trigger.Trigger, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_channel(self, + request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> channel.Channel: + r"""Get a single Channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelRequest( + name="name_value", + ) + + # Make the request + response = client.get_channel(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetChannelRequest, dict]): + The request object. The request message for the + GetChannel method. + name (str): + Required. The name of the channel 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Channel: + A representation of the Channel + resource. A Channel is a resource on + which event providers publish their + events. The published events are + delivered through the transport + associated with the channel. Note that a + channel is associated with exactly one + event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetChannelRequest): + request = eventarc.GetChannelRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_channel] + + # Certain 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_channels(self, + request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChannelsPager: + r"""List channels. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_channels(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channels(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListChannelsRequest, dict]): + The request object. The request message for the + ListChannels method. + parent (str): + Required. The parent collection to + list channels on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsPager: + The response message for the ListChannels method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListChannelsRequest): + request = eventarc.ListChannelsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_channels] + + # Certain 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.ListChannelsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_channel(self, + request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[gce_channel.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new channel in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + channel = eventarc_v1.Channel() + channel.pubsub_topic = "pubsub_topic_value" + channel.name = "name_value" + + request = eventarc_v1.CreateChannelRequest( + parent="parent_value", + channel=channel, + channel_id="channel_id_value", + ) + + # Make the request + operation = client.create_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateChannelRequest, dict]): + The request object. The request message for the + CreateChannel method. + parent (str): + Required. The parent collection in + which to add this channel. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel (google.cloud.eventarc_v1.types.Channel): + Required. The channel to create. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_id (str): + Required. The user-provided ID to be + assigned to the channel. + + This corresponds to the ``channel_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. + A Channel is a resource on which event providers + publish their events. The published events are + delivered through the transport associated with the + channel. Note that a channel is associated with + exactly one event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel, channel_id]) + if request is 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, eventarc.CreateChannelRequest): + request = eventarc.CreateChannelRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel is not None: + request.channel = channel + if channel_id is not None: + request.channel_id = channel_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_channel_] + + # Certain 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, + gce_channel.Channel, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_channel(self, + request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, + *, + channel: Optional[gce_channel.Channel] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateChannelRequest( + ) + + # Make the request + operation = client.update_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateChannelRequest, dict]): + The request object. The request message for the + UpdateChannel method. + channel (google.cloud.eventarc_v1.types.Channel): + The channel to be updated. + This corresponds to the ``channel`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update + all fields, provide a field mask of "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. + A Channel is a resource on which event providers + publish their events. The published events are + delivered through the transport associated with the + channel. Note that a channel is associated with + exactly one event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([channel, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.UpdateChannelRequest): + request = eventarc.UpdateChannelRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if channel is not None: + request.channel = channel + 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_channel] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("channel.name", request.channel.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, + gce_channel.Channel, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_channel(self, + request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteChannelRequest, dict]): + The request object. The request message for the + DeleteChannel method. + name (str): + Required. The name of the channel to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. + A Channel is a resource on which event providers + publish their events. The published events are + delivered through the transport associated with the + channel. Note that a channel is associated with + exactly one event provider. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.DeleteChannelRequest): + request = eventarc.DeleteChannelRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_channel] + + # Certain 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, + channel.Channel, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_provider(self, + request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> discovery.Provider: + r"""Get a single Provider. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_provider(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetProviderRequest( + name="name_value", + ) + + # Make the request + response = client.get_provider(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetProviderRequest, dict]): + The request object. The request message for the + GetProvider method. + name (str): + Required. The name of the provider 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Provider: + A representation of the Provider + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetProviderRequest): + request = eventarc.GetProviderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_provider] + + # Certain 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_providers(self, + request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProvidersPager: + r"""List providers. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_providers(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_providers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListProvidersRequest, dict]): + The request object. The request message for the + ListProviders method. + parent (str): + Required. The parent of the provider + to get. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersPager: + The response message for the ListProviders method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListProvidersRequest): + request = eventarc.ListProvidersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_providers] + + # Certain 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.ListProvidersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_channel_connection(self, + request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> channel_connection.ChannelConnection: + r"""Get a single ChannelConnection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_channel_connection(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelConnectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_channel_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetChannelConnectionRequest, dict]): + The request object. The request message for the + GetChannelConnection method. + name (str): + Required. The name of the channel + connection 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.ChannelConnection: + A representation of the + ChannelConnection resource. A + ChannelConnection is a resource which + event providers create during the + activation process to establish a + connection between the provider and the + subscriber channel. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetChannelConnectionRequest): + request = eventarc.GetChannelConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_channel_connection] + + # Certain 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_channel_connections(self, + request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListChannelConnectionsPager: + r"""List channel connections. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_channel_connections(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channel_connections(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListChannelConnectionsRequest, dict]): + The request object. The request message for the + ListChannelConnections method. + parent (str): + Required. The parent collection from + which to list channel connections. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsPager: + The response message for the ListChannelConnections + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListChannelConnectionsRequest): + request = eventarc.ListChannelConnectionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_channel_connections] + + # Certain 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.ListChannelConnectionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_channel_connection(self, + request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, + channel_connection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new ChannelConnection in a particular + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_channel_connection(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + channel_connection = eventarc_v1.ChannelConnection() + channel_connection.name = "name_value" + channel_connection.channel = "channel_value" + + request = eventarc_v1.CreateChannelConnectionRequest( + parent="parent_value", + channel_connection=channel_connection, + channel_connection_id="channel_connection_id_value", + ) + + # Make the request + operation = client.create_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateChannelConnectionRequest, dict]): + The request object. The request message for the + CreateChannelConnection method. + parent (str): + Required. The parent collection in + which to add this channel connection. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_connection (google.cloud.eventarc_v1.types.ChannelConnection): + Required. Channel connection to + create. + + This corresponds to the ``channel_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_connection_id (str): + Required. The user-provided ID to be + assigned to the channel connection. + + This corresponds to the ``channel_connection_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. + A ChannelConnection is a resource which event + providers create during the activation process to + establish a connection between the provider and the + subscriber channel. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel_connection, channel_connection_id]) + if request is 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, eventarc.CreateChannelConnectionRequest): + request = eventarc.CreateChannelConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel_connection is not None: + request.channel_connection = channel_connection + if channel_connection_id is not None: + request.channel_connection_id = channel_connection_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_channel_connection] + + # Certain 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, + gce_channel_connection.ChannelConnection, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_channel_connection(self, + request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single ChannelConnection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_channel_connection(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelConnectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest, dict]): + The request object. The request message for the + DeleteChannelConnection method. + name (str): + Required. The name of the channel + connection 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. + A ChannelConnection is a resource which event + providers create during the activation process to + establish a connection between the provider and the + subscriber channel. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.DeleteChannelConnectionRequest): + request = eventarc.DeleteChannelConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_channel_connection] + + # Certain 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, + channel_connection.ChannelConnection, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_google_channel_config(self, + request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_channel_config.GoogleChannelConfig: + r"""Get a GoogleChannelConfig + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleChannelConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_google_channel_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest, dict]): + The request object. The request message for the + GetGoogleChannelConfig method. + name (str): + Required. The name of the config 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetGoogleChannelConfigRequest): + request = eventarc.GetGoogleChannelConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_google_channel_config] + + # Certain 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_google_channel_config(self, + request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, + *, + google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: + r"""Update a single GoogleChannelConfig + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_channel_config = eventarc_v1.GoogleChannelConfig() + google_channel_config.name = "name_value" + + request = eventarc_v1.UpdateGoogleChannelConfigRequest( + google_channel_config=google_channel_config, + ) + + # Make the request + response = client.update_google_channel_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest, dict]): + The request object. The request message for the + UpdateGoogleChannelConfig method. + google_channel_config (google.cloud.eventarc_v1.types.GoogleChannelConfig): + Required. The config to be updated. + This corresponds to the ``google_channel_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update + all fields, provide a field mask of "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_channel_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.UpdateGoogleChannelConfigRequest): + request = eventarc.UpdateGoogleChannelConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_channel_config is not None: + request.google_channel_config = google_channel_config + 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_google_channel_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_channel_config.name", request.google_channel_config.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 get_message_bus(self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message_bus.MessageBus: + r"""Get a single MessageBus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = client.get_message_bus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetMessageBusRequest, dict]): + The request object. The request message for the + GetMessageBus method. + name (str): + Required. The name of the message bus + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.MessageBus: + MessageBus for the messages flowing + through the system. The admin has + visibility and control over the messages + being published and consumed and can + restrict publishers and subscribers to + only a subset of data available in the + system by defining authorization + policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetMessageBusRequest): + request = eventarc.GetMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_message_bus] + + # Certain 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_message_buses(self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusesPager: + r"""List message buses. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListMessageBusesRequest, dict]): + The request object. The request message for the + ListMessageBuses method. + parent (str): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesPager: + The response message for the ListMessageBuses method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListMessageBusesRequest): + request = eventarc.ListMessageBusesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message_buses] + + # Certain 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.ListMessageBusesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_message_bus_enrollments(self, + request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusEnrollmentsPager: + r"""List message bus enrollments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest, dict]): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + parent (str): + Required. The parent message bus to + list enrollments on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsPager: + The response message for the ListMessageBusEnrollments + method.\` + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListMessageBusEnrollmentsRequest): + request = eventarc.ListMessageBusEnrollmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message_bus_enrollments] + + # Certain 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.ListMessageBusEnrollmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_message_bus(self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new MessageBus in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateMessageBusRequest, dict]): + The request object. The request message for the + CreateMessageBus method. + parent (str): + Required. The parent collection in + which to add this message bus. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The message bus to create. + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus_id (str): + Required. The user-provided ID to be assigned to the + MessageBus. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + + This corresponds to the ``message_bus_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, message_bus, message_bus_id]) + if request is 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, eventarc.CreateMessageBusRequest): + request = eventarc.CreateMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message_bus is not None: + request.message_bus = message_bus + if message_bus_id is not None: + request.message_bus_id = message_bus_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_message_bus] + + # Certain 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, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_message_bus(self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single message bus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateMessageBusRequest, dict]): + The request object. The request message for the + UpdateMessageBus method. + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The MessageBus to be + updated. + + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([message_bus, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.UpdateMessageBusRequest): + request = eventarc.UpdateMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message_bus is not None: + request.message_bus = message_bus + 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_message_bus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("message_bus.name", request.message_bus.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, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_message_bus(self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single message bus. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteMessageBusRequest, dict]): + The request object. The request message for the + DeleteMessageBus method. + name (str): + Required. The name of the MessageBus + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeleteMessageBusRequest): + request = eventarc.DeleteMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_message_bus] + + # Certain 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, + message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_enrollment(self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> enrollment.Enrollment: + r"""Get a single Enrollment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_enrollment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetEnrollmentRequest, dict]): + The request object. The request message for the + GetEnrollment method. + name (str): + Required. The name of the Enrollment + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Enrollment: + An enrollment represents a + subscription for messages on a + particular message bus. It defines a + matching criteria for messages on the + bus and the subscriber endpoint where + matched messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetEnrollmentRequest): + request = eventarc.GetEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_enrollment] + + # Certain 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_enrollments(self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnrollmentsPager: + r"""List Enrollments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListEnrollmentsRequest, dict]): + The request object. The request message for the + ListEnrollments method. + parent (str): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsPager: + The response message for the ListEnrollments method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListEnrollmentsRequest): + request = eventarc.ListEnrollmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_enrollments] + + # Certain 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.ListEnrollmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_enrollment(self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new Enrollment in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateEnrollmentRequest, dict]): + The request object. The request message for the + CreateEnrollment method. + parent (str): + Required. The parent collection in + which to add this enrollment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The enrollment to create. + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment_id (str): + Required. The user-provided ID to be assigned to the + Enrollment. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``enrollment_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, enrollment, enrollment_id]) + if request is 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, eventarc.CreateEnrollmentRequest): + request = eventarc.CreateEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if enrollment is not None: + request.enrollment = enrollment + if enrollment_id is not None: + request.enrollment_id = enrollment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_enrollment] + + # Certain 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, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_enrollment(self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single Enrollment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateEnrollmentRequest, dict]): + The request object. The request message for the + UpdateEnrollment method. + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The Enrollment to be + updated. + + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([enrollment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.UpdateEnrollmentRequest): + request = eventarc.UpdateEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enrollment is not None: + request.enrollment = enrollment + 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_enrollment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("enrollment.name", request.enrollment.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, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_enrollment(self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single Enrollment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteEnrollmentRequest, dict]): + The request object. The request message for the + DeleteEnrollment method. + name (str): + Required. The name of the Enrollment + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the Enrollment + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeleteEnrollmentRequest): + request = eventarc.DeleteEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_enrollment] + + # Certain 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, + enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_pipeline(self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pipeline.Pipeline: + r"""Get a single Pipeline. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = client.get_pipeline(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetPipelineRequest, dict]): + The request object. The request message for the + GetPipeline method. + name (str): + Required. The name of the pipeline 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Pipeline: + A representation of the Pipeline + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetPipelineRequest): + request = eventarc.GetPipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_pipeline] + + # Certain 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_pipelines(self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPipelinesPager: + r"""List pipelines. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListPipelinesRequest, dict]): + The request object. The request message for the + ListPipelines method. + parent (str): + Required. The parent collection to + list pipelines on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesPager: + The response message for the + ListPipelines method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListPipelinesRequest): + request = eventarc.ListPipelinesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_pipelines] + + # Certain 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.ListPipelinesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_pipeline(self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new Pipeline in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreatePipelineRequest, dict]): + The request object. The request message for the + CreatePipeline method. + parent (str): + Required. The parent collection in + which to add this pipeline. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The pipeline to create. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline_id (str): + Required. The user-provided ID to be + assigned to the Pipeline. + + This corresponds to the ``pipeline_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, pipeline, pipeline_id]) + if request is 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, eventarc.CreatePipelineRequest): + request = eventarc.CreatePipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if pipeline is not None: + request.pipeline = pipeline + if pipeline_id is not None: + request.pipeline_id = pipeline_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_pipeline] + + # Certain 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, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_pipeline(self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single pipeline. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdatePipelineRequest, dict]): + The request object. The request message for the + UpdatePipeline method. + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The Pipeline to be updated. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([pipeline, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.UpdatePipelineRequest): + request = eventarc.UpdatePipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if pipeline is not None: + request.pipeline = pipeline + 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_pipeline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("pipeline.name", request.pipeline.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, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_pipeline(self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single pipeline. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeletePipelineRequest, dict]): + The request object. The request message for the + DeletePipeline method. + name (str): + Required. The name of the Pipeline to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the Pipeline + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeletePipelineRequest): + request = eventarc.DeletePipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_pipeline] + + # Certain 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, + pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_google_api_source(self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_api_source.GoogleApiSource: + r"""Get a single GoogleApiSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_google_api_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest, dict]): + The request object. The request message for the + GetGoogleApiSource method. + name (str): + Required. The name of the google api + source 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleApiSource: + A GoogleApiSource represents a + subscription of 1P events from a + MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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, eventarc.GetGoogleApiSourceRequest): + request = eventarc.GetGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_google_api_source] + + # Certain 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_google_api_sources(self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGoogleApiSourcesPager: + r"""List GoogleApiSources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest, dict]): + The request object. The request message for the + ListGoogleApiSources method. + parent (str): + Required. The parent collection to + list GoogleApiSources on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesPager: + The response message for the ListGoogleApiSources + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.ListGoogleApiSourcesRequest): + request = eventarc.ListGoogleApiSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_google_api_sources] + + # Certain 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.ListGoogleApiSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_google_api_source(self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new GoogleApiSource in a particular project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest, dict]): + The request object. The request message for the + CreateGoogleApiSource method. + parent (str): + Required. The parent collection in + which to add this google api source. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The google api source to + create. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source_id (str): + Required. The user-provided ID to be assigned to the + GoogleApiSource. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``google_api_source_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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, google_api_source, google_api_source_id]) + if request is 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, eventarc.CreateGoogleApiSourceRequest): + request = eventarc.CreateGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_api_source is not None: + request.google_api_source = google_api_source + if google_api_source_id is not None: + request.google_api_source_id = google_api_source_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_google_api_source] + + # Certain 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, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_google_api_source(self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single GoogleApiSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest, dict]): + The request object. The request message for the + UpdateGoogleApiSource method. + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The GoogleApiSource to be + updated. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_api_source, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - 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, eventarc.UpdateGoogleApiSourceRequest): + request = eventarc.UpdateGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_api_source is not None: + request.google_api_source = google_api_source + 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_google_api_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_api_source.name", request.google_api_source.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, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_google_api_source(self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single GoogleApiSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest, dict]): + The request object. The request message for the + DeleteGoogleApiSource method. + name (str): + Required. The name of the + GoogleApiSource to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, etag]) + if request is 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, eventarc.DeleteGoogleApiSourceRequest): + request = eventarc.DeleteGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_google_api_source] + + # Certain 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, + google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EventarcClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.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 cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = 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() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EventarcClient", +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py new file mode 100644 index 000000000000..3e7b93bf7b7e --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py @@ -0,0 +1,1250 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +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.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger + + +class ListTriggersPager: + """A pager for iterating through ``list_triggers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``triggers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTriggers`` requests and continue to iterate + through the ``triggers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListTriggersResponse], + request: eventarc.ListTriggersRequest, + response: eventarc.ListTriggersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListTriggersRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListTriggersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListTriggersRequest(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[eventarc.ListTriggersResponse]: + 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[trigger.Trigger]: + for page in self.pages: + yield from page.triggers + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTriggersAsyncPager: + """A pager for iterating through ``list_triggers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``triggers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTriggers`` requests and continue to iterate + through the ``triggers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` + attributes are available on the 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[eventarc.ListTriggersResponse]], + request: eventarc.ListTriggersRequest, + response: eventarc.ListTriggersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListTriggersRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListTriggersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListTriggersRequest(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[eventarc.ListTriggersResponse]: + 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[trigger.Trigger]: + async def async_generator(): + async for page in self.pages: + for response in page.triggers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListChannelsPager: + """A pager for iterating through ``list_channels`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``channels`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChannels`` requests and continue to iterate + through the ``channels`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListChannelsResponse], + request: eventarc.ListChannelsRequest, + response: eventarc.ListChannelsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListChannelsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListChannelsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListChannelsRequest(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[eventarc.ListChannelsResponse]: + 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[channel.Channel]: + for page in self.pages: + yield from page.channels + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListChannelsAsyncPager: + """A pager for iterating through ``list_channels`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``channels`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChannels`` requests and continue to iterate + through the ``channels`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` + attributes are available on the 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[eventarc.ListChannelsResponse]], + request: eventarc.ListChannelsRequest, + response: eventarc.ListChannelsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListChannelsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListChannelsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListChannelsRequest(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[eventarc.ListChannelsResponse]: + 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[channel.Channel]: + async def async_generator(): + async for page in self.pages: + for response in page.channels: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProvidersPager: + """A pager for iterating through ``list_providers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``providers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProviders`` requests and continue to iterate + through the ``providers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListProvidersResponse], + request: eventarc.ListProvidersRequest, + response: eventarc.ListProvidersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListProvidersRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListProvidersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListProvidersRequest(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[eventarc.ListProvidersResponse]: + 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[discovery.Provider]: + for page in self.pages: + yield from page.providers + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProvidersAsyncPager: + """A pager for iterating through ``list_providers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``providers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProviders`` requests and continue to iterate + through the ``providers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` + attributes are available on the 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[eventarc.ListProvidersResponse]], + request: eventarc.ListProvidersRequest, + response: eventarc.ListProvidersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListProvidersRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListProvidersResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListProvidersRequest(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[eventarc.ListProvidersResponse]: + 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[discovery.Provider]: + async def async_generator(): + async for page in self.pages: + for response in page.providers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListChannelConnectionsPager: + """A pager for iterating through ``list_channel_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``channel_connections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChannelConnections`` requests and continue to iterate + through the ``channel_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListChannelConnectionsResponse], + request: eventarc.ListChannelConnectionsRequest, + response: eventarc.ListChannelConnectionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListChannelConnectionsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListChannelConnectionsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListChannelConnectionsRequest(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[eventarc.ListChannelConnectionsResponse]: + 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[channel_connection.ChannelConnection]: + for page in self.pages: + yield from page.channel_connections + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListChannelConnectionsAsyncPager: + """A pager for iterating through ``list_channel_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``channel_connections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChannelConnections`` requests and continue to iterate + through the ``channel_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` + attributes are available on the 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[eventarc.ListChannelConnectionsResponse]], + request: eventarc.ListChannelConnectionsRequest, + response: eventarc.ListChannelConnectionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListChannelConnectionsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListChannelConnectionsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListChannelConnectionsRequest(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[eventarc.ListChannelConnectionsResponse]: + 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[channel_connection.ChannelConnection]: + async def async_generator(): + async for page in self.pages: + for response in page.channel_connections: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessageBusesPager: + """A pager for iterating through ``list_message_buses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``message_buses`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessageBuses`` requests and continue to iterate + through the ``message_buses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListMessageBusesResponse], + request: eventarc.ListMessageBusesRequest, + response: eventarc.ListMessageBusesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusesRequest(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[eventarc.ListMessageBusesResponse]: + 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[message_bus.MessageBus]: + for page in self.pages: + yield from page.message_buses + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessageBusesAsyncPager: + """A pager for iterating through ``list_message_buses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``message_buses`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessageBuses`` requests and continue to iterate + through the ``message_buses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` + attributes are available on the 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[eventarc.ListMessageBusesResponse]], + request: eventarc.ListMessageBusesRequest, + response: eventarc.ListMessageBusesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusesRequest(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[eventarc.ListMessageBusesResponse]: + 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[message_bus.MessageBus]: + async def async_generator(): + async for page in self.pages: + for response in page.message_buses: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessageBusEnrollmentsPager: + """A pager for iterating through ``list_message_bus_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessageBusEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListMessageBusEnrollmentsResponse], + request: eventarc.ListMessageBusEnrollmentsRequest, + response: eventarc.ListMessageBusEnrollmentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusEnrollmentsRequest(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[eventarc.ListMessageBusEnrollmentsResponse]: + 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[str]: + for page in self.pages: + yield from page.enrollments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessageBusEnrollmentsAsyncPager: + """A pager for iterating through ``list_message_bus_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessageBusEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` + attributes are available on the 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[eventarc.ListMessageBusEnrollmentsResponse]], + request: eventarc.ListMessageBusEnrollmentsRequest, + response: eventarc.ListMessageBusEnrollmentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusEnrollmentsRequest(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[eventarc.ListMessageBusEnrollmentsResponse]: + 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[str]: + async def async_generator(): + async for page in self.pages: + for response in page.enrollments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnrollmentsPager: + """A pager for iterating through ``list_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListEnrollmentsResponse], + request: eventarc.ListEnrollmentsRequest, + response: eventarc.ListEnrollmentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListEnrollmentsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListEnrollmentsRequest(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[eventarc.ListEnrollmentsResponse]: + 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[enrollment.Enrollment]: + for page in self.pages: + yield from page.enrollments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnrollmentsAsyncPager: + """A pager for iterating through ``list_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` + attributes are available on the 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[eventarc.ListEnrollmentsResponse]], + request: eventarc.ListEnrollmentsRequest, + response: eventarc.ListEnrollmentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListEnrollmentsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListEnrollmentsRequest(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[eventarc.ListEnrollmentsResponse]: + 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[enrollment.Enrollment]: + async def async_generator(): + async for page in self.pages: + for response in page.enrollments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPipelinesPager: + """A pager for iterating through ``list_pipelines`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``pipelines`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPipelines`` requests and continue to iterate + through the ``pipelines`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListPipelinesResponse], + request: eventarc.ListPipelinesRequest, + response: eventarc.ListPipelinesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListPipelinesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListPipelinesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListPipelinesRequest(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[eventarc.ListPipelinesResponse]: + 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[pipeline.Pipeline]: + for page in self.pages: + yield from page.pipelines + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPipelinesAsyncPager: + """A pager for iterating through ``list_pipelines`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``pipelines`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPipelines`` requests and continue to iterate + through the ``pipelines`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` + attributes are available on the 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[eventarc.ListPipelinesResponse]], + request: eventarc.ListPipelinesRequest, + response: eventarc.ListPipelinesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListPipelinesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListPipelinesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListPipelinesRequest(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[eventarc.ListPipelinesResponse]: + 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[pipeline.Pipeline]: + async def async_generator(): + async for page in self.pages: + for response in page.pipelines: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGoogleApiSourcesPager: + """A pager for iterating through ``list_google_api_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``google_api_sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGoogleApiSources`` requests and continue to iterate + through the ``google_api_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., eventarc.ListGoogleApiSourcesResponse], + request: eventarc.ListGoogleApiSourcesRequest, + response: eventarc.ListGoogleApiSourcesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListGoogleApiSourcesRequest(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[eventarc.ListGoogleApiSourcesResponse]: + 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[google_api_source.GoogleApiSource]: + for page in self.pages: + yield from page.google_api_sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGoogleApiSourcesAsyncPager: + """A pager for iterating through ``list_google_api_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``google_api_sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGoogleApiSources`` requests and continue to iterate + through the ``google_api_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` + attributes are available on the 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[eventarc.ListGoogleApiSourcesResponse]], + request: eventarc.ListGoogleApiSourcesRequest, + response: eventarc.ListGoogleApiSourcesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListGoogleApiSourcesRequest(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[eventarc.ListGoogleApiSourcesResponse]: + 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[google_api_source.GoogleApiSource]: + async def async_generator(): + async for page in self.pages: + for response in page.google_api_sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst new file mode 100644 index 000000000000..442d2fb0c1b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EventarcTransport` is the ABC for all transports. +- public child `EventarcGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EventarcGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEventarcRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EventarcRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py new file mode 100644 index 000000000000..afed78b17c2c --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 EventarcTransport +from .grpc import EventarcGrpcTransport +from .grpc_asyncio import EventarcGrpcAsyncIOTransport +from .rest import EventarcRestTransport +from .rest import EventarcRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EventarcTransport]] +_transport_registry['grpc'] = EventarcGrpcTransport +_transport_registry['grpc_asyncio'] = EventarcGrpcAsyncIOTransport +_transport_registry['rest'] = EventarcRestTransport + +__all__ = ( + 'EventarcTransport', + 'EventarcGrpcTransport', + 'EventarcGrpcAsyncIOTransport', + 'EventarcRestTransport', + 'EventarcRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py new file mode 100644 index 000000000000..9c0558d2afd3 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -0,0 +1,1013 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.eventarc_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +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 + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class EventarcTransport(abc.ABC): + """Abstract transport class for Eventarc.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'eventarc.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: 'eventarc.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if 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.get_trigger: gapic_v1.method.wrap_method( + self.get_trigger, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_triggers: gapic_v1.method.wrap_method( + self.list_triggers, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_trigger: gapic_v1.method.wrap_method( + self.create_trigger, + default_timeout=60.0, + client_info=client_info, + ), + self.update_trigger: gapic_v1.method.wrap_method( + self.update_trigger, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_trigger: gapic_v1.method.wrap_method( + self.delete_trigger, + default_timeout=60.0, + client_info=client_info, + ), + self.get_channel: gapic_v1.method.wrap_method( + self.get_channel, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_channels: gapic_v1.method.wrap_method( + self.list_channels, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_channel_: gapic_v1.method.wrap_method( + self.create_channel_, + default_timeout=60.0, + client_info=client_info, + ), + self.update_channel: gapic_v1.method.wrap_method( + self.update_channel, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_channel: gapic_v1.method.wrap_method( + self.delete_channel, + default_timeout=60.0, + client_info=client_info, + ), + self.get_provider: gapic_v1.method.wrap_method( + self.get_provider, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_providers: gapic_v1.method.wrap_method( + self.list_providers, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_channel_connection: gapic_v1.method.wrap_method( + self.get_channel_connection, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_channel_connections: gapic_v1.method.wrap_method( + self.list_channel_connections, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_channel_connection: gapic_v1.method.wrap_method( + self.create_channel_connection, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_channel_connection: gapic_v1.method.wrap_method( + self.delete_channel_connection, + default_timeout=60.0, + client_info=client_info, + ), + self.get_google_channel_config: gapic_v1.method.wrap_method( + self.get_google_channel_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_channel_config: gapic_v1.method.wrap_method( + self.update_google_channel_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_message_bus: gapic_v1.method.wrap_method( + self.get_message_bus, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_buses: gapic_v1.method.wrap_method( + self.list_message_buses, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_bus_enrollments: gapic_v1.method.wrap_method( + self.list_message_bus_enrollments, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_message_bus: gapic_v1.method.wrap_method( + self.create_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.update_message_bus: gapic_v1.method.wrap_method( + self.update_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_message_bus: gapic_v1.method.wrap_method( + self.delete_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.get_enrollment: gapic_v1.method.wrap_method( + self.get_enrollment, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_enrollments: gapic_v1.method.wrap_method( + self.list_enrollments, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_enrollment: gapic_v1.method.wrap_method( + self.create_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.update_enrollment: gapic_v1.method.wrap_method( + self.update_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_enrollment: gapic_v1.method.wrap_method( + self.delete_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.get_pipeline: gapic_v1.method.wrap_method( + self.get_pipeline, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_pipelines: gapic_v1.method.wrap_method( + self.list_pipelines, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_pipeline: gapic_v1.method.wrap_method( + self.create_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.update_pipeline: gapic_v1.method.wrap_method( + self.update_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_pipeline: gapic_v1.method.wrap_method( + self.delete_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.get_google_api_source: gapic_v1.method.wrap_method( + self.get_google_api_source, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_google_api_sources: gapic_v1.method.wrap_method( + self.list_google_api_sources, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_google_api_source: gapic_v1.method.wrap_method( + self.create_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_api_source: gapic_v1.method.wrap_method( + self.update_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_google_api_source: gapic_v1.method.wrap_method( + self.delete_google_api_source, + 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.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + 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, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_trigger(self) -> Callable[ + [eventarc.GetTriggerRequest], + Union[ + trigger.Trigger, + Awaitable[trigger.Trigger] + ]]: + raise NotImplementedError() + + @property + def list_triggers(self) -> Callable[ + [eventarc.ListTriggersRequest], + Union[ + eventarc.ListTriggersResponse, + Awaitable[eventarc.ListTriggersResponse] + ]]: + raise NotImplementedError() + + @property + def create_trigger(self) -> Callable[ + [eventarc.CreateTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_trigger(self) -> Callable[ + [eventarc.UpdateTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_trigger(self) -> Callable[ + [eventarc.DeleteTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_channel(self) -> Callable[ + [eventarc.GetChannelRequest], + Union[ + channel.Channel, + Awaitable[channel.Channel] + ]]: + raise NotImplementedError() + + @property + def list_channels(self) -> Callable[ + [eventarc.ListChannelsRequest], + Union[ + eventarc.ListChannelsResponse, + Awaitable[eventarc.ListChannelsResponse] + ]]: + raise NotImplementedError() + + @property + def create_channel_(self) -> Callable[ + [eventarc.CreateChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_channel(self) -> Callable[ + [eventarc.UpdateChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_channel(self) -> Callable[ + [eventarc.DeleteChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_provider(self) -> Callable[ + [eventarc.GetProviderRequest], + Union[ + discovery.Provider, + Awaitable[discovery.Provider] + ]]: + raise NotImplementedError() + + @property + def list_providers(self) -> Callable[ + [eventarc.ListProvidersRequest], + Union[ + eventarc.ListProvidersResponse, + Awaitable[eventarc.ListProvidersResponse] + ]]: + raise NotImplementedError() + + @property + def get_channel_connection(self) -> Callable[ + [eventarc.GetChannelConnectionRequest], + Union[ + channel_connection.ChannelConnection, + Awaitable[channel_connection.ChannelConnection] + ]]: + raise NotImplementedError() + + @property + def list_channel_connections(self) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + Union[ + eventarc.ListChannelConnectionsResponse, + Awaitable[eventarc.ListChannelConnectionsResponse] + ]]: + raise NotImplementedError() + + @property + def create_channel_connection(self) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_channel_connection(self) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_google_channel_config(self) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + Union[ + google_channel_config.GoogleChannelConfig, + Awaitable[google_channel_config.GoogleChannelConfig] + ]]: + raise NotImplementedError() + + @property + def update_google_channel_config(self) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + Union[ + gce_google_channel_config.GoogleChannelConfig, + Awaitable[gce_google_channel_config.GoogleChannelConfig] + ]]: + raise NotImplementedError() + + @property + def get_message_bus(self) -> Callable[ + [eventarc.GetMessageBusRequest], + Union[ + message_bus.MessageBus, + Awaitable[message_bus.MessageBus] + ]]: + raise NotImplementedError() + + @property + def list_message_buses(self) -> Callable[ + [eventarc.ListMessageBusesRequest], + Union[ + eventarc.ListMessageBusesResponse, + Awaitable[eventarc.ListMessageBusesResponse] + ]]: + raise NotImplementedError() + + @property + def list_message_bus_enrollments(self) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Union[ + eventarc.ListMessageBusEnrollmentsResponse, + Awaitable[eventarc.ListMessageBusEnrollmentsResponse] + ]]: + raise NotImplementedError() + + @property + def create_message_bus(self) -> Callable[ + [eventarc.CreateMessageBusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_message_bus(self) -> Callable[ + [eventarc.UpdateMessageBusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_message_bus(self) -> Callable[ + [eventarc.DeleteMessageBusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_enrollment(self) -> Callable[ + [eventarc.GetEnrollmentRequest], + Union[ + enrollment.Enrollment, + Awaitable[enrollment.Enrollment] + ]]: + raise NotImplementedError() + + @property + def list_enrollments(self) -> Callable[ + [eventarc.ListEnrollmentsRequest], + Union[ + eventarc.ListEnrollmentsResponse, + Awaitable[eventarc.ListEnrollmentsResponse] + ]]: + raise NotImplementedError() + + @property + def create_enrollment(self) -> Callable[ + [eventarc.CreateEnrollmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_enrollment(self) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_enrollment(self) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_pipeline(self) -> Callable[ + [eventarc.GetPipelineRequest], + Union[ + pipeline.Pipeline, + Awaitable[pipeline.Pipeline] + ]]: + raise NotImplementedError() + + @property + def list_pipelines(self) -> Callable[ + [eventarc.ListPipelinesRequest], + Union[ + eventarc.ListPipelinesResponse, + Awaitable[eventarc.ListPipelinesResponse] + ]]: + raise NotImplementedError() + + @property + def create_pipeline(self) -> Callable[ + [eventarc.CreatePipelineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_pipeline(self) -> Callable[ + [eventarc.UpdatePipelineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_pipeline(self) -> Callable[ + [eventarc.DeletePipelineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_google_api_source(self) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Union[ + google_api_source.GoogleApiSource, + Awaitable[google_api_source.GoogleApiSource] + ]]: + raise NotImplementedError() + + @property + def list_google_api_sources(self) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Union[ + eventarc.ListGoogleApiSourcesResponse, + Awaitable[eventarc.ListGoogleApiSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def create_google_api_source(self) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_google_api_source(self) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_google_api_source(self) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + 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__ = ( + 'EventarcTransport', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py new file mode 100644 index 000000000000..4fa4923170a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -0,0 +1,1486 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +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 .base import EventarcTransport, DEFAULT_CLIENT_INFO + + +class EventarcGrpcTransport(EventarcTransport): + """gRPC backend transport for Eventarc. + + Eventarc allows users to subscribe to various events that are + provided by Google Cloud services and forward them to supported + destinations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'eventarc.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: 'eventarc.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]): 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. + 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'eventarc.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_trigger(self) -> Callable[ + [eventarc.GetTriggerRequest], + trigger.Trigger]: + r"""Return a callable for the get trigger method over gRPC. + + Get a single trigger. + + Returns: + Callable[[~.GetTriggerRequest], + ~.Trigger]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_trigger' not in self._stubs: + self._stubs['get_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetTrigger', + request_serializer=eventarc.GetTriggerRequest.serialize, + response_deserializer=trigger.Trigger.deserialize, + ) + return self._stubs['get_trigger'] + + @property + def list_triggers(self) -> Callable[ + [eventarc.ListTriggersRequest], + eventarc.ListTriggersResponse]: + r"""Return a callable for the list triggers method over gRPC. + + List triggers. + + Returns: + Callable[[~.ListTriggersRequest], + ~.ListTriggersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_triggers' not in self._stubs: + self._stubs['list_triggers'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListTriggers', + request_serializer=eventarc.ListTriggersRequest.serialize, + response_deserializer=eventarc.ListTriggersResponse.deserialize, + ) + return self._stubs['list_triggers'] + + @property + def create_trigger(self) -> Callable[ + [eventarc.CreateTriggerRequest], + operations_pb2.Operation]: + r"""Return a callable for the create trigger method over gRPC. + + Create a new trigger in a particular project and + location. + + Returns: + Callable[[~.CreateTriggerRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_trigger' not in self._stubs: + self._stubs['create_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateTrigger', + request_serializer=eventarc.CreateTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_trigger'] + + @property + def update_trigger(self) -> Callable[ + [eventarc.UpdateTriggerRequest], + operations_pb2.Operation]: + r"""Return a callable for the update trigger method over gRPC. + + Update a single trigger. + + Returns: + Callable[[~.UpdateTriggerRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_trigger' not in self._stubs: + self._stubs['update_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', + request_serializer=eventarc.UpdateTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_trigger'] + + @property + def delete_trigger(self) -> Callable[ + [eventarc.DeleteTriggerRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete trigger method over gRPC. + + Delete a single trigger. + + Returns: + Callable[[~.DeleteTriggerRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_trigger' not in self._stubs: + self._stubs['delete_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', + request_serializer=eventarc.DeleteTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_trigger'] + + @property + def get_channel(self) -> Callable[ + [eventarc.GetChannelRequest], + channel.Channel]: + r"""Return a callable for the get channel method over gRPC. + + Get a single Channel. + + Returns: + Callable[[~.GetChannelRequest], + ~.Channel]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_channel' not in self._stubs: + self._stubs['get_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetChannel', + request_serializer=eventarc.GetChannelRequest.serialize, + response_deserializer=channel.Channel.deserialize, + ) + return self._stubs['get_channel'] + + @property + def list_channels(self) -> Callable[ + [eventarc.ListChannelsRequest], + eventarc.ListChannelsResponse]: + r"""Return a callable for the list channels method over gRPC. + + List channels. + + Returns: + Callable[[~.ListChannelsRequest], + ~.ListChannelsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_channels' not in self._stubs: + self._stubs['list_channels'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListChannels', + request_serializer=eventarc.ListChannelsRequest.serialize, + response_deserializer=eventarc.ListChannelsResponse.deserialize, + ) + return self._stubs['list_channels'] + + @property + def create_channel_(self) -> Callable[ + [eventarc.CreateChannelRequest], + operations_pb2.Operation]: + r"""Return a callable for the create channel method over gRPC. + + Create a new channel in a particular project and + location. + + Returns: + Callable[[~.CreateChannelRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_channel_' not in self._stubs: + self._stubs['create_channel_'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateChannel', + request_serializer=eventarc.CreateChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_channel_'] + + @property + def update_channel(self) -> Callable[ + [eventarc.UpdateChannelRequest], + operations_pb2.Operation]: + r"""Return a callable for the update channel method over gRPC. + + Update a single channel. + + Returns: + Callable[[~.UpdateChannelRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_channel' not in self._stubs: + self._stubs['update_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateChannel', + request_serializer=eventarc.UpdateChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_channel'] + + @property + def delete_channel(self) -> Callable[ + [eventarc.DeleteChannelRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete channel method over gRPC. + + Delete a single channel. + + Returns: + Callable[[~.DeleteChannelRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel' not in self._stubs: + self._stubs['delete_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteChannel', + request_serializer=eventarc.DeleteChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_channel'] + + @property + def get_provider(self) -> Callable[ + [eventarc.GetProviderRequest], + discovery.Provider]: + r"""Return a callable for the get provider method over gRPC. + + Get a single Provider. + + Returns: + Callable[[~.GetProviderRequest], + ~.Provider]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_provider' not in self._stubs: + self._stubs['get_provider'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetProvider', + request_serializer=eventarc.GetProviderRequest.serialize, + response_deserializer=discovery.Provider.deserialize, + ) + return self._stubs['get_provider'] + + @property + def list_providers(self) -> Callable[ + [eventarc.ListProvidersRequest], + eventarc.ListProvidersResponse]: + r"""Return a callable for the list providers method over gRPC. + + List providers. + + Returns: + Callable[[~.ListProvidersRequest], + ~.ListProvidersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_providers' not in self._stubs: + self._stubs['list_providers'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListProviders', + request_serializer=eventarc.ListProvidersRequest.serialize, + response_deserializer=eventarc.ListProvidersResponse.deserialize, + ) + return self._stubs['list_providers'] + + @property + def get_channel_connection(self) -> Callable[ + [eventarc.GetChannelConnectionRequest], + channel_connection.ChannelConnection]: + r"""Return a callable for the get channel connection method over gRPC. + + Get a single ChannelConnection. + + Returns: + Callable[[~.GetChannelConnectionRequest], + ~.ChannelConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_channel_connection' not in self._stubs: + self._stubs['get_channel_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', + request_serializer=eventarc.GetChannelConnectionRequest.serialize, + response_deserializer=channel_connection.ChannelConnection.deserialize, + ) + return self._stubs['get_channel_connection'] + + @property + def list_channel_connections(self) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + eventarc.ListChannelConnectionsResponse]: + r"""Return a callable for the list channel connections method over gRPC. + + List channel connections. + + Returns: + Callable[[~.ListChannelConnectionsRequest], + ~.ListChannelConnectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_channel_connections' not in self._stubs: + self._stubs['list_channel_connections'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', + request_serializer=eventarc.ListChannelConnectionsRequest.serialize, + response_deserializer=eventarc.ListChannelConnectionsResponse.deserialize, + ) + return self._stubs['list_channel_connections'] + + @property + def create_channel_connection(self) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create channel connection method over gRPC. + + Create a new ChannelConnection in a particular + project and location. + + Returns: + Callable[[~.CreateChannelConnectionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_channel_connection' not in self._stubs: + self._stubs['create_channel_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', + request_serializer=eventarc.CreateChannelConnectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_channel_connection'] + + @property + def delete_channel_connection(self) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete channel connection method over gRPC. + + Delete a single ChannelConnection. + + Returns: + Callable[[~.DeleteChannelConnectionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_connection' not in self._stubs: + self._stubs['delete_channel_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', + request_serializer=eventarc.DeleteChannelConnectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_channel_connection'] + + @property + def get_google_channel_config(self) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + google_channel_config.GoogleChannelConfig]: + r"""Return a callable for the get google channel config method over gRPC. + + Get a GoogleChannelConfig + + Returns: + Callable[[~.GetGoogleChannelConfigRequest], + ~.GoogleChannelConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_google_channel_config' not in self._stubs: + self._stubs['get_google_channel_config'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig', + request_serializer=eventarc.GetGoogleChannelConfigRequest.serialize, + response_deserializer=google_channel_config.GoogleChannelConfig.deserialize, + ) + return self._stubs['get_google_channel_config'] + + @property + def update_google_channel_config(self) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + gce_google_channel_config.GoogleChannelConfig]: + r"""Return a callable for the update google channel config method over gRPC. + + Update a single GoogleChannelConfig + + Returns: + Callable[[~.UpdateGoogleChannelConfigRequest], + ~.GoogleChannelConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_google_channel_config' not in self._stubs: + self._stubs['update_google_channel_config'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig', + request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, + response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, + ) + return self._stubs['update_google_channel_config'] + + @property + def get_message_bus(self) -> Callable[ + [eventarc.GetMessageBusRequest], + message_bus.MessageBus]: + r"""Return a callable for the get message bus method over gRPC. + + Get a single MessageBus. + + Returns: + Callable[[~.GetMessageBusRequest], + ~.MessageBus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_message_bus' not in self._stubs: + self._stubs['get_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetMessageBus', + request_serializer=eventarc.GetMessageBusRequest.serialize, + response_deserializer=message_bus.MessageBus.deserialize, + ) + return self._stubs['get_message_bus'] + + @property + def list_message_buses(self) -> Callable[ + [eventarc.ListMessageBusesRequest], + eventarc.ListMessageBusesResponse]: + r"""Return a callable for the list message buses method over gRPC. + + List message buses. + + Returns: + Callable[[~.ListMessageBusesRequest], + ~.ListMessageBusesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_message_buses' not in self._stubs: + self._stubs['list_message_buses'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListMessageBuses', + request_serializer=eventarc.ListMessageBusesRequest.serialize, + response_deserializer=eventarc.ListMessageBusesResponse.deserialize, + ) + return self._stubs['list_message_buses'] + + @property + def list_message_bus_enrollments(self) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse]: + r"""Return a callable for the list message bus enrollments method over gRPC. + + List message bus enrollments. + + Returns: + Callable[[~.ListMessageBusEnrollmentsRequest], + ~.ListMessageBusEnrollmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_message_bus_enrollments' not in self._stubs: + self._stubs['list_message_bus_enrollments'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments', + request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, + ) + return self._stubs['list_message_bus_enrollments'] + + @property + def create_message_bus(self) -> Callable[ + [eventarc.CreateMessageBusRequest], + operations_pb2.Operation]: + r"""Return a callable for the create message bus method over gRPC. + + Create a new MessageBus in a particular project and + location. + + Returns: + Callable[[~.CreateMessageBusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_message_bus' not in self._stubs: + self._stubs['create_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateMessageBus', + request_serializer=eventarc.CreateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_message_bus'] + + @property + def update_message_bus(self) -> Callable[ + [eventarc.UpdateMessageBusRequest], + operations_pb2.Operation]: + r"""Return a callable for the update message bus method over gRPC. + + Update a single message bus. + + Returns: + Callable[[~.UpdateMessageBusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_message_bus' not in self._stubs: + self._stubs['update_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus', + request_serializer=eventarc.UpdateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_message_bus'] + + @property + def delete_message_bus(self) -> Callable[ + [eventarc.DeleteMessageBusRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete message bus method over gRPC. + + Delete a single message bus. + + Returns: + Callable[[~.DeleteMessageBusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message_bus' not in self._stubs: + self._stubs['delete_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus', + request_serializer=eventarc.DeleteMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_message_bus'] + + @property + def get_enrollment(self) -> Callable[ + [eventarc.GetEnrollmentRequest], + enrollment.Enrollment]: + r"""Return a callable for the get enrollment method over gRPC. + + Get a single Enrollment. + + Returns: + Callable[[~.GetEnrollmentRequest], + ~.Enrollment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_enrollment' not in self._stubs: + self._stubs['get_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetEnrollment', + request_serializer=eventarc.GetEnrollmentRequest.serialize, + response_deserializer=enrollment.Enrollment.deserialize, + ) + return self._stubs['get_enrollment'] + + @property + def list_enrollments(self) -> Callable[ + [eventarc.ListEnrollmentsRequest], + eventarc.ListEnrollmentsResponse]: + r"""Return a callable for the list enrollments method over gRPC. + + List Enrollments. + + Returns: + Callable[[~.ListEnrollmentsRequest], + ~.ListEnrollmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_enrollments' not in self._stubs: + self._stubs['list_enrollments'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListEnrollments', + request_serializer=eventarc.ListEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, + ) + return self._stubs['list_enrollments'] + + @property + def create_enrollment(self) -> Callable[ + [eventarc.CreateEnrollmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create enrollment method over gRPC. + + Create a new Enrollment in a particular project and + location. + + Returns: + Callable[[~.CreateEnrollmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_enrollment' not in self._stubs: + self._stubs['create_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateEnrollment', + request_serializer=eventarc.CreateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_enrollment'] + + @property + def update_enrollment(self) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update enrollment method over gRPC. + + Update a single Enrollment. + + Returns: + Callable[[~.UpdateEnrollmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_enrollment' not in self._stubs: + self._stubs['update_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment', + request_serializer=eventarc.UpdateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_enrollment'] + + @property + def delete_enrollment(self) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete enrollment method over gRPC. + + Delete a single Enrollment. + + Returns: + Callable[[~.DeleteEnrollmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_enrollment' not in self._stubs: + self._stubs['delete_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment', + request_serializer=eventarc.DeleteEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_enrollment'] + + @property + def get_pipeline(self) -> Callable[ + [eventarc.GetPipelineRequest], + pipeline.Pipeline]: + r"""Return a callable for the get pipeline method over gRPC. + + Get a single Pipeline. + + Returns: + Callable[[~.GetPipelineRequest], + ~.Pipeline]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_pipeline' not in self._stubs: + self._stubs['get_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetPipeline', + request_serializer=eventarc.GetPipelineRequest.serialize, + response_deserializer=pipeline.Pipeline.deserialize, + ) + return self._stubs['get_pipeline'] + + @property + def list_pipelines(self) -> Callable[ + [eventarc.ListPipelinesRequest], + eventarc.ListPipelinesResponse]: + r"""Return a callable for the list pipelines method over gRPC. + + List pipelines. + + Returns: + Callable[[~.ListPipelinesRequest], + ~.ListPipelinesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pipelines' not in self._stubs: + self._stubs['list_pipelines'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListPipelines', + request_serializer=eventarc.ListPipelinesRequest.serialize, + response_deserializer=eventarc.ListPipelinesResponse.deserialize, + ) + return self._stubs['list_pipelines'] + + @property + def create_pipeline(self) -> Callable[ + [eventarc.CreatePipelineRequest], + operations_pb2.Operation]: + r"""Return a callable for the create pipeline method over gRPC. + + Create a new Pipeline in a particular project and + location. + + Returns: + Callable[[~.CreatePipelineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_pipeline' not in self._stubs: + self._stubs['create_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreatePipeline', + request_serializer=eventarc.CreatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_pipeline'] + + @property + def update_pipeline(self) -> Callable[ + [eventarc.UpdatePipelineRequest], + operations_pb2.Operation]: + r"""Return a callable for the update pipeline method over gRPC. + + Update a single pipeline. + + Returns: + Callable[[~.UpdatePipelineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_pipeline' not in self._stubs: + self._stubs['update_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdatePipeline', + request_serializer=eventarc.UpdatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_pipeline'] + + @property + def delete_pipeline(self) -> Callable[ + [eventarc.DeletePipelineRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete pipeline method over gRPC. + + Delete a single pipeline. + + Returns: + Callable[[~.DeletePipelineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_pipeline' not in self._stubs: + self._stubs['delete_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeletePipeline', + request_serializer=eventarc.DeletePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_pipeline'] + + @property + def get_google_api_source(self) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + google_api_source.GoogleApiSource]: + r"""Return a callable for the get google api source method over gRPC. + + Get a single GoogleApiSource. + + Returns: + Callable[[~.GetGoogleApiSourceRequest], + ~.GoogleApiSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_google_api_source' not in self._stubs: + self._stubs['get_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource', + request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, + response_deserializer=google_api_source.GoogleApiSource.deserialize, + ) + return self._stubs['get_google_api_source'] + + @property + def list_google_api_sources(self) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + eventarc.ListGoogleApiSourcesResponse]: + r"""Return a callable for the list google api sources method over gRPC. + + List GoogleApiSources. + + Returns: + Callable[[~.ListGoogleApiSourcesRequest], + ~.ListGoogleApiSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_google_api_sources' not in self._stubs: + self._stubs['list_google_api_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources', + request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, + response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, + ) + return self._stubs['list_google_api_sources'] + + @property + def create_google_api_source(self) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create google api source method over gRPC. + + Create a new GoogleApiSource in a particular project + and location. + + Returns: + Callable[[~.CreateGoogleApiSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_google_api_source' not in self._stubs: + self._stubs['create_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource', + request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_google_api_source'] + + @property + def update_google_api_source(self) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update google api source method over gRPC. + + Update a single GoogleApiSource. + + Returns: + Callable[[~.UpdateGoogleApiSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_google_api_source' not in self._stubs: + self._stubs['update_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource', + request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_google_api_source'] + + @property + def delete_google_api_source(self) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete google api source method over gRPC. + + Delete a single GoogleApiSource. + + Returns: + Callable[[~.DeleteGoogleApiSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_api_source' not in self._stubs: + self._stubs['delete_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource', + request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_google_api_source'] + + def close(self): + self.grpc_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.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def 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.grpc_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.grpc_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.grpc_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__ = ( + 'EventarcGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9411c3f57461 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py @@ -0,0 +1,1922 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +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 .base import EventarcTransport, DEFAULT_CLIENT_INFO +from .grpc import EventarcGrpcTransport + + +class EventarcGrpcAsyncIOTransport(EventarcTransport): + """gRPC AsyncIO backend transport for Eventarc. + + Eventarc allows users to subscribe to various events that are + provided by Google Cloud services and forward them to supported + destinations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'eventarc.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (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 = 'eventarc.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: 'eventarc.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]): 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. + scopes (Optional[Sequence[str]]): A optional 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_trigger(self) -> Callable[ + [eventarc.GetTriggerRequest], + Awaitable[trigger.Trigger]]: + r"""Return a callable for the get trigger method over gRPC. + + Get a single trigger. + + Returns: + Callable[[~.GetTriggerRequest], + Awaitable[~.Trigger]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_trigger' not in self._stubs: + self._stubs['get_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetTrigger', + request_serializer=eventarc.GetTriggerRequest.serialize, + response_deserializer=trigger.Trigger.deserialize, + ) + return self._stubs['get_trigger'] + + @property + def list_triggers(self) -> Callable[ + [eventarc.ListTriggersRequest], + Awaitable[eventarc.ListTriggersResponse]]: + r"""Return a callable for the list triggers method over gRPC. + + List triggers. + + Returns: + Callable[[~.ListTriggersRequest], + Awaitable[~.ListTriggersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_triggers' not in self._stubs: + self._stubs['list_triggers'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListTriggers', + request_serializer=eventarc.ListTriggersRequest.serialize, + response_deserializer=eventarc.ListTriggersResponse.deserialize, + ) + return self._stubs['list_triggers'] + + @property + def create_trigger(self) -> Callable[ + [eventarc.CreateTriggerRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create trigger method over gRPC. + + Create a new trigger in a particular project and + location. + + Returns: + Callable[[~.CreateTriggerRequest], + 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_trigger' not in self._stubs: + self._stubs['create_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateTrigger', + request_serializer=eventarc.CreateTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_trigger'] + + @property + def update_trigger(self) -> Callable[ + [eventarc.UpdateTriggerRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update trigger method over gRPC. + + Update a single trigger. + + Returns: + Callable[[~.UpdateTriggerRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_trigger' not in self._stubs: + self._stubs['update_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', + request_serializer=eventarc.UpdateTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_trigger'] + + @property + def delete_trigger(self) -> Callable[ + [eventarc.DeleteTriggerRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete trigger method over gRPC. + + Delete a single trigger. + + Returns: + Callable[[~.DeleteTriggerRequest], + 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_trigger' not in self._stubs: + self._stubs['delete_trigger'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', + request_serializer=eventarc.DeleteTriggerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_trigger'] + + @property + def get_channel(self) -> Callable[ + [eventarc.GetChannelRequest], + Awaitable[channel.Channel]]: + r"""Return a callable for the get channel method over gRPC. + + Get a single Channel. + + Returns: + Callable[[~.GetChannelRequest], + Awaitable[~.Channel]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_channel' not in self._stubs: + self._stubs['get_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetChannel', + request_serializer=eventarc.GetChannelRequest.serialize, + response_deserializer=channel.Channel.deserialize, + ) + return self._stubs['get_channel'] + + @property + def list_channels(self) -> Callable[ + [eventarc.ListChannelsRequest], + Awaitable[eventarc.ListChannelsResponse]]: + r"""Return a callable for the list channels method over gRPC. + + List channels. + + Returns: + Callable[[~.ListChannelsRequest], + Awaitable[~.ListChannelsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_channels' not in self._stubs: + self._stubs['list_channels'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListChannels', + request_serializer=eventarc.ListChannelsRequest.serialize, + response_deserializer=eventarc.ListChannelsResponse.deserialize, + ) + return self._stubs['list_channels'] + + @property + def create_channel_(self) -> Callable[ + [eventarc.CreateChannelRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create channel method over gRPC. + + Create a new channel in a particular project and + location. + + Returns: + Callable[[~.CreateChannelRequest], + 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_channel_' not in self._stubs: + self._stubs['create_channel_'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateChannel', + request_serializer=eventarc.CreateChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_channel_'] + + @property + def update_channel(self) -> Callable[ + [eventarc.UpdateChannelRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update channel method over gRPC. + + Update a single channel. + + Returns: + Callable[[~.UpdateChannelRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_channel' not in self._stubs: + self._stubs['update_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateChannel', + request_serializer=eventarc.UpdateChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_channel'] + + @property + def delete_channel(self) -> Callable[ + [eventarc.DeleteChannelRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete channel method over gRPC. + + Delete a single channel. + + Returns: + Callable[[~.DeleteChannelRequest], + 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_channel' not in self._stubs: + self._stubs['delete_channel'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteChannel', + request_serializer=eventarc.DeleteChannelRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_channel'] + + @property + def get_provider(self) -> Callable[ + [eventarc.GetProviderRequest], + Awaitable[discovery.Provider]]: + r"""Return a callable for the get provider method over gRPC. + + Get a single Provider. + + Returns: + Callable[[~.GetProviderRequest], + Awaitable[~.Provider]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_provider' not in self._stubs: + self._stubs['get_provider'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetProvider', + request_serializer=eventarc.GetProviderRequest.serialize, + response_deserializer=discovery.Provider.deserialize, + ) + return self._stubs['get_provider'] + + @property + def list_providers(self) -> Callable[ + [eventarc.ListProvidersRequest], + Awaitable[eventarc.ListProvidersResponse]]: + r"""Return a callable for the list providers method over gRPC. + + List providers. + + Returns: + Callable[[~.ListProvidersRequest], + Awaitable[~.ListProvidersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_providers' not in self._stubs: + self._stubs['list_providers'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListProviders', + request_serializer=eventarc.ListProvidersRequest.serialize, + response_deserializer=eventarc.ListProvidersResponse.deserialize, + ) + return self._stubs['list_providers'] + + @property + def get_channel_connection(self) -> Callable[ + [eventarc.GetChannelConnectionRequest], + Awaitable[channel_connection.ChannelConnection]]: + r"""Return a callable for the get channel connection method over gRPC. + + Get a single ChannelConnection. + + Returns: + Callable[[~.GetChannelConnectionRequest], + Awaitable[~.ChannelConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_channel_connection' not in self._stubs: + self._stubs['get_channel_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', + request_serializer=eventarc.GetChannelConnectionRequest.serialize, + response_deserializer=channel_connection.ChannelConnection.deserialize, + ) + return self._stubs['get_channel_connection'] + + @property + def list_channel_connections(self) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + Awaitable[eventarc.ListChannelConnectionsResponse]]: + r"""Return a callable for the list channel connections method over gRPC. + + List channel connections. + + Returns: + Callable[[~.ListChannelConnectionsRequest], + Awaitable[~.ListChannelConnectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_channel_connections' not in self._stubs: + self._stubs['list_channel_connections'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', + request_serializer=eventarc.ListChannelConnectionsRequest.serialize, + response_deserializer=eventarc.ListChannelConnectionsResponse.deserialize, + ) + return self._stubs['list_channel_connections'] + + @property + def create_channel_connection(self) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create channel connection method over gRPC. + + Create a new ChannelConnection in a particular + project and location. + + Returns: + Callable[[~.CreateChannelConnectionRequest], + 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_channel_connection' not in self._stubs: + self._stubs['create_channel_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', + request_serializer=eventarc.CreateChannelConnectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_channel_connection'] + + @property + def delete_channel_connection(self) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete channel connection method over gRPC. + + Delete a single ChannelConnection. + + Returns: + Callable[[~.DeleteChannelConnectionRequest], + 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_channel_connection' not in self._stubs: + self._stubs['delete_channel_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', + request_serializer=eventarc.DeleteChannelConnectionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_channel_connection'] + + @property + def get_google_channel_config(self) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + Awaitable[google_channel_config.GoogleChannelConfig]]: + r"""Return a callable for the get google channel config method over gRPC. + + Get a GoogleChannelConfig + + Returns: + Callable[[~.GetGoogleChannelConfigRequest], + Awaitable[~.GoogleChannelConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_google_channel_config' not in self._stubs: + self._stubs['get_google_channel_config'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig', + request_serializer=eventarc.GetGoogleChannelConfigRequest.serialize, + response_deserializer=google_channel_config.GoogleChannelConfig.deserialize, + ) + return self._stubs['get_google_channel_config'] + + @property + def update_google_channel_config(self) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + Awaitable[gce_google_channel_config.GoogleChannelConfig]]: + r"""Return a callable for the update google channel config method over gRPC. + + Update a single GoogleChannelConfig + + Returns: + Callable[[~.UpdateGoogleChannelConfigRequest], + Awaitable[~.GoogleChannelConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_google_channel_config' not in self._stubs: + self._stubs['update_google_channel_config'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig', + request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, + response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, + ) + return self._stubs['update_google_channel_config'] + + @property + def get_message_bus(self) -> Callable[ + [eventarc.GetMessageBusRequest], + Awaitable[message_bus.MessageBus]]: + r"""Return a callable for the get message bus method over gRPC. + + Get a single MessageBus. + + Returns: + Callable[[~.GetMessageBusRequest], + Awaitable[~.MessageBus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_message_bus' not in self._stubs: + self._stubs['get_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetMessageBus', + request_serializer=eventarc.GetMessageBusRequest.serialize, + response_deserializer=message_bus.MessageBus.deserialize, + ) + return self._stubs['get_message_bus'] + + @property + def list_message_buses(self) -> Callable[ + [eventarc.ListMessageBusesRequest], + Awaitable[eventarc.ListMessageBusesResponse]]: + r"""Return a callable for the list message buses method over gRPC. + + List message buses. + + Returns: + Callable[[~.ListMessageBusesRequest], + Awaitable[~.ListMessageBusesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_message_buses' not in self._stubs: + self._stubs['list_message_buses'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListMessageBuses', + request_serializer=eventarc.ListMessageBusesRequest.serialize, + response_deserializer=eventarc.ListMessageBusesResponse.deserialize, + ) + return self._stubs['list_message_buses'] + + @property + def list_message_bus_enrollments(self) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Awaitable[eventarc.ListMessageBusEnrollmentsResponse]]: + r"""Return a callable for the list message bus enrollments method over gRPC. + + List message bus enrollments. + + Returns: + Callable[[~.ListMessageBusEnrollmentsRequest], + Awaitable[~.ListMessageBusEnrollmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_message_bus_enrollments' not in self._stubs: + self._stubs['list_message_bus_enrollments'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments', + request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, + ) + return self._stubs['list_message_bus_enrollments'] + + @property + def create_message_bus(self) -> Callable[ + [eventarc.CreateMessageBusRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create message bus method over gRPC. + + Create a new MessageBus in a particular project and + location. + + Returns: + Callable[[~.CreateMessageBusRequest], + 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_message_bus' not in self._stubs: + self._stubs['create_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateMessageBus', + request_serializer=eventarc.CreateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_message_bus'] + + @property + def update_message_bus(self) -> Callable[ + [eventarc.UpdateMessageBusRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update message bus method over gRPC. + + Update a single message bus. + + Returns: + Callable[[~.UpdateMessageBusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_message_bus' not in self._stubs: + self._stubs['update_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus', + request_serializer=eventarc.UpdateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_message_bus'] + + @property + def delete_message_bus(self) -> Callable[ + [eventarc.DeleteMessageBusRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete message bus method over gRPC. + + Delete a single message bus. + + Returns: + Callable[[~.DeleteMessageBusRequest], + 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_message_bus' not in self._stubs: + self._stubs['delete_message_bus'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus', + request_serializer=eventarc.DeleteMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_message_bus'] + + @property + def get_enrollment(self) -> Callable[ + [eventarc.GetEnrollmentRequest], + Awaitable[enrollment.Enrollment]]: + r"""Return a callable for the get enrollment method over gRPC. + + Get a single Enrollment. + + Returns: + Callable[[~.GetEnrollmentRequest], + Awaitable[~.Enrollment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_enrollment' not in self._stubs: + self._stubs['get_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetEnrollment', + request_serializer=eventarc.GetEnrollmentRequest.serialize, + response_deserializer=enrollment.Enrollment.deserialize, + ) + return self._stubs['get_enrollment'] + + @property + def list_enrollments(self) -> Callable[ + [eventarc.ListEnrollmentsRequest], + Awaitable[eventarc.ListEnrollmentsResponse]]: + r"""Return a callable for the list enrollments method over gRPC. + + List Enrollments. + + Returns: + Callable[[~.ListEnrollmentsRequest], + Awaitable[~.ListEnrollmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_enrollments' not in self._stubs: + self._stubs['list_enrollments'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListEnrollments', + request_serializer=eventarc.ListEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, + ) + return self._stubs['list_enrollments'] + + @property + def create_enrollment(self) -> Callable[ + [eventarc.CreateEnrollmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create enrollment method over gRPC. + + Create a new Enrollment in a particular project and + location. + + Returns: + Callable[[~.CreateEnrollmentRequest], + 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_enrollment' not in self._stubs: + self._stubs['create_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateEnrollment', + request_serializer=eventarc.CreateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_enrollment'] + + @property + def update_enrollment(self) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update enrollment method over gRPC. + + Update a single Enrollment. + + Returns: + Callable[[~.UpdateEnrollmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_enrollment' not in self._stubs: + self._stubs['update_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment', + request_serializer=eventarc.UpdateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_enrollment'] + + @property + def delete_enrollment(self) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete enrollment method over gRPC. + + Delete a single Enrollment. + + Returns: + Callable[[~.DeleteEnrollmentRequest], + 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_enrollment' not in self._stubs: + self._stubs['delete_enrollment'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment', + request_serializer=eventarc.DeleteEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_enrollment'] + + @property + def get_pipeline(self) -> Callable[ + [eventarc.GetPipelineRequest], + Awaitable[pipeline.Pipeline]]: + r"""Return a callable for the get pipeline method over gRPC. + + Get a single Pipeline. + + Returns: + Callable[[~.GetPipelineRequest], + Awaitable[~.Pipeline]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_pipeline' not in self._stubs: + self._stubs['get_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetPipeline', + request_serializer=eventarc.GetPipelineRequest.serialize, + response_deserializer=pipeline.Pipeline.deserialize, + ) + return self._stubs['get_pipeline'] + + @property + def list_pipelines(self) -> Callable[ + [eventarc.ListPipelinesRequest], + Awaitable[eventarc.ListPipelinesResponse]]: + r"""Return a callable for the list pipelines method over gRPC. + + List pipelines. + + Returns: + Callable[[~.ListPipelinesRequest], + Awaitable[~.ListPipelinesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pipelines' not in self._stubs: + self._stubs['list_pipelines'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListPipelines', + request_serializer=eventarc.ListPipelinesRequest.serialize, + response_deserializer=eventarc.ListPipelinesResponse.deserialize, + ) + return self._stubs['list_pipelines'] + + @property + def create_pipeline(self) -> Callable[ + [eventarc.CreatePipelineRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create pipeline method over gRPC. + + Create a new Pipeline in a particular project and + location. + + Returns: + Callable[[~.CreatePipelineRequest], + 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_pipeline' not in self._stubs: + self._stubs['create_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreatePipeline', + request_serializer=eventarc.CreatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_pipeline'] + + @property + def update_pipeline(self) -> Callable[ + [eventarc.UpdatePipelineRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update pipeline method over gRPC. + + Update a single pipeline. + + Returns: + Callable[[~.UpdatePipelineRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_pipeline' not in self._stubs: + self._stubs['update_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdatePipeline', + request_serializer=eventarc.UpdatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_pipeline'] + + @property + def delete_pipeline(self) -> Callable[ + [eventarc.DeletePipelineRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete pipeline method over gRPC. + + Delete a single pipeline. + + Returns: + Callable[[~.DeletePipelineRequest], + 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_pipeline' not in self._stubs: + self._stubs['delete_pipeline'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeletePipeline', + request_serializer=eventarc.DeletePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_pipeline'] + + @property + def get_google_api_source(self) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Awaitable[google_api_source.GoogleApiSource]]: + r"""Return a callable for the get google api source method over gRPC. + + Get a single GoogleApiSource. + + Returns: + Callable[[~.GetGoogleApiSourceRequest], + Awaitable[~.GoogleApiSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_google_api_source' not in self._stubs: + self._stubs['get_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource', + request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, + response_deserializer=google_api_source.GoogleApiSource.deserialize, + ) + return self._stubs['get_google_api_source'] + + @property + def list_google_api_sources(self) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Awaitable[eventarc.ListGoogleApiSourcesResponse]]: + r"""Return a callable for the list google api sources method over gRPC. + + List GoogleApiSources. + + Returns: + Callable[[~.ListGoogleApiSourcesRequest], + Awaitable[~.ListGoogleApiSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_google_api_sources' not in self._stubs: + self._stubs['list_google_api_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources', + request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, + response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, + ) + return self._stubs['list_google_api_sources'] + + @property + def create_google_api_source(self) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create google api source method over gRPC. + + Create a new GoogleApiSource in a particular project + and location. + + Returns: + Callable[[~.CreateGoogleApiSourceRequest], + 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_google_api_source' not in self._stubs: + self._stubs['create_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource', + request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_google_api_source'] + + @property + def update_google_api_source(self) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update google api source method over gRPC. + + Update a single GoogleApiSource. + + Returns: + Callable[[~.UpdateGoogleApiSourceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_google_api_source' not in self._stubs: + self._stubs['update_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource', + request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_google_api_source'] + + @property + def delete_google_api_source(self) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete google api source method over gRPC. + + Delete a single GoogleApiSource. + + Returns: + Callable[[~.DeleteGoogleApiSourceRequest], + 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_google_api_source' not in self._stubs: + self._stubs['delete_google_api_source'] = self.grpc_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource', + request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_google_api_source'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_trigger: self._wrap_method( + self.get_trigger, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_triggers: self._wrap_method( + self.list_triggers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_trigger: self._wrap_method( + self.create_trigger, + default_timeout=60.0, + client_info=client_info, + ), + self.update_trigger: self._wrap_method( + self.update_trigger, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_trigger: self._wrap_method( + self.delete_trigger, + default_timeout=60.0, + client_info=client_info, + ), + self.get_channel: self._wrap_method( + self.get_channel, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_channels: self._wrap_method( + self.list_channels, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_channel_: self._wrap_method( + self.create_channel_, + default_timeout=60.0, + client_info=client_info, + ), + self.update_channel: self._wrap_method( + self.update_channel, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_channel: self._wrap_method( + self.delete_channel, + default_timeout=60.0, + client_info=client_info, + ), + self.get_provider: self._wrap_method( + self.get_provider, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_providers: self._wrap_method( + self.list_providers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_channel_connection: self._wrap_method( + self.get_channel_connection, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_channel_connections: self._wrap_method( + self.list_channel_connections, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_channel_connection: self._wrap_method( + self.create_channel_connection, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_channel_connection: self._wrap_method( + self.delete_channel_connection, + default_timeout=60.0, + client_info=client_info, + ), + self.get_google_channel_config: self._wrap_method( + self.get_google_channel_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_channel_config: self._wrap_method( + self.update_google_channel_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_message_bus: self._wrap_method( + self.get_message_bus, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_buses: self._wrap_method( + self.list_message_buses, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_bus_enrollments: self._wrap_method( + self.list_message_bus_enrollments, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_message_bus: self._wrap_method( + self.create_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.update_message_bus: self._wrap_method( + self.update_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_message_bus: self._wrap_method( + self.delete_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.get_enrollment: self._wrap_method( + self.get_enrollment, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_enrollments: self._wrap_method( + self.list_enrollments, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_enrollment: self._wrap_method( + self.create_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.update_enrollment: self._wrap_method( + self.update_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_enrollment: self._wrap_method( + self.delete_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.get_pipeline: self._wrap_method( + self.get_pipeline, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_pipelines: self._wrap_method( + self.list_pipelines, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_pipeline: self._wrap_method( + self.create_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.update_pipeline: self._wrap_method( + self.update_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_pipeline: self._wrap_method( + self.delete_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.get_google_api_source: self._wrap_method( + self.get_google_api_source, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_google_api_sources: self._wrap_method( + self.list_google_api_sources, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_google_api_source: self._wrap_method( + self.create_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_api_source: self._wrap_method( + self.update_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_google_api_source: self._wrap_method( + self.delete_google_api_source, + 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.cancel_operation: self._wrap_method( + self.cancel_operation, + 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, + ), + } + + 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.grpc_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.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def 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.grpc_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.grpc_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.grpc_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__ = ( + 'EventarcGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py new file mode 100644 index 000000000000..0b189dff714f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py @@ -0,0 +1,5300 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseEventarcRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +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}", +) + + +class EventarcRestInterceptor: + """Interceptor for Eventarc. + + 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 EventarcRestTransport. + + .. code-block:: python + class MyCustomEventarcInterceptor(EventarcRestInterceptor): + def pre_create_channel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_channel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_channel_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_channel_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_channel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_channel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_channel_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_channel_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_channel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_channel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_channel_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_channel_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_google_channel_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_google_channel_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_provider(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_provider(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_channel_connections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_channel_connections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_channels(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_channels(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_enrollments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_enrollments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_google_api_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_google_api_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_message_bus_enrollments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_message_bus_enrollments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_message_buses(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_message_buses(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_pipelines(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_pipelines(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_providers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_providers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_triggers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_triggers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_channel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_channel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_google_channel_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_google_channel_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EventarcRestTransport(interceptor=MyCustomEventarcInterceptor()) + client = EventarcClient(transport=transport) + + + """ + def pre_create_channel(self, request: eventarc.CreateChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_channel + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_channel + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_create_channel_connection(self, request: eventarc.CreateChannelConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateChannelConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_channel_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_channel_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_channel_connection + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_create_enrollment(self, request: eventarc.CreateEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_enrollment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_enrollment + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_create_google_api_source(self, request: eventarc.CreateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_google_api_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_google_api_source + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_create_message_bus(self, request: eventarc.CreateMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_message_bus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_message_bus + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_create_pipeline(self, request: eventarc.CreatePipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreatePipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_pipeline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_pipeline + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_create_trigger(self, request: eventarc.CreateTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_create_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_trigger + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_channel(self, request: eventarc.DeleteChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_channel + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_channel + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_channel_connection(self, request: eventarc.DeleteChannelConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteChannelConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_channel_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_channel_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_channel_connection + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_enrollment(self, request: eventarc.DeleteEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_enrollment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_enrollment + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_google_api_source(self, request: eventarc.DeleteGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_google_api_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_google_api_source + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_message_bus(self, request: eventarc.DeleteMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_message_bus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_message_bus + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_pipeline(self, request: eventarc.DeletePipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeletePipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_pipeline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_pipeline + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_trigger(self, request: eventarc.DeleteTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_trigger + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_channel(self, request: eventarc.GetChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_channel + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_channel(self, response: channel.Channel) -> channel.Channel: + """Post-rpc interceptor for get_channel + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_channel_connection(self, request: eventarc.GetChannelConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetChannelConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_channel_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_channel_connection(self, response: channel_connection.ChannelConnection) -> channel_connection.ChannelConnection: + """Post-rpc interceptor for get_channel_connection + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_enrollment(self, request: eventarc.GetEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_enrollment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_enrollment(self, response: enrollment.Enrollment) -> enrollment.Enrollment: + """Post-rpc interceptor for get_enrollment + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_google_api_source(self, request: eventarc.GetGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_google_api_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_google_api_source(self, response: google_api_source.GoogleApiSource) -> google_api_source.GoogleApiSource: + """Post-rpc interceptor for get_google_api_source + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_google_channel_config(self, request: eventarc.GetGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_google_channel_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_google_channel_config(self, response: google_channel_config.GoogleChannelConfig) -> google_channel_config.GoogleChannelConfig: + """Post-rpc interceptor for get_google_channel_config + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_message_bus(self, request: eventarc.GetMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_message_bus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_message_bus(self, response: message_bus.MessageBus) -> message_bus.MessageBus: + """Post-rpc interceptor for get_message_bus + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_pipeline(self, request: eventarc.GetPipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetPipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_pipeline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_pipeline(self, response: pipeline.Pipeline) -> pipeline.Pipeline: + """Post-rpc interceptor for get_pipeline + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_provider(self, request: eventarc.GetProviderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetProviderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_provider + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_provider(self, response: discovery.Provider) -> discovery.Provider: + """Post-rpc interceptor for get_provider + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_trigger(self, request: eventarc.GetTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_trigger(self, response: trigger.Trigger) -> trigger.Trigger: + """Post-rpc interceptor for get_trigger + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_channel_connections(self, request: eventarc.ListChannelConnectionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListChannelConnectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_channel_connections + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_channel_connections(self, response: eventarc.ListChannelConnectionsResponse) -> eventarc.ListChannelConnectionsResponse: + """Post-rpc interceptor for list_channel_connections + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_channels(self, request: eventarc.ListChannelsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListChannelsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_channels + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_channels(self, response: eventarc.ListChannelsResponse) -> eventarc.ListChannelsResponse: + """Post-rpc interceptor for list_channels + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_enrollments(self, request: eventarc.ListEnrollmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListEnrollmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_enrollments + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_enrollments(self, response: eventarc.ListEnrollmentsResponse) -> eventarc.ListEnrollmentsResponse: + """Post-rpc interceptor for list_enrollments + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_google_api_sources(self, request: eventarc.ListGoogleApiSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListGoogleApiSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_google_api_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_google_api_sources(self, response: eventarc.ListGoogleApiSourcesResponse) -> eventarc.ListGoogleApiSourcesResponse: + """Post-rpc interceptor for list_google_api_sources + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_message_bus_enrollments(self, request: eventarc.ListMessageBusEnrollmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListMessageBusEnrollmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_message_bus_enrollments + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_message_bus_enrollments(self, response: eventarc.ListMessageBusEnrollmentsResponse) -> eventarc.ListMessageBusEnrollmentsResponse: + """Post-rpc interceptor for list_message_bus_enrollments + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_message_buses(self, request: eventarc.ListMessageBusesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListMessageBusesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_message_buses + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_message_buses(self, response: eventarc.ListMessageBusesResponse) -> eventarc.ListMessageBusesResponse: + """Post-rpc interceptor for list_message_buses + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_pipelines(self, request: eventarc.ListPipelinesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListPipelinesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_pipelines + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_pipelines(self, response: eventarc.ListPipelinesResponse) -> eventarc.ListPipelinesResponse: + """Post-rpc interceptor for list_pipelines + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_providers(self, request: eventarc.ListProvidersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListProvidersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_providers + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_providers(self, response: eventarc.ListProvidersResponse) -> eventarc.ListProvidersResponse: + """Post-rpc interceptor for list_providers + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_triggers(self, request: eventarc.ListTriggersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListTriggersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_triggers + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_triggers(self, response: eventarc.ListTriggersResponse) -> eventarc.ListTriggersResponse: + """Post-rpc interceptor for list_triggers + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_channel(self, request: eventarc.UpdateChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_channel + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_channel + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_enrollment(self, request: eventarc.UpdateEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_enrollment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_enrollment + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_google_api_source(self, request: eventarc.UpdateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_api_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_google_api_source + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_google_channel_config(self, request: eventarc.UpdateGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_channel_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_google_channel_config(self, response: gce_google_channel_config.GoogleChannelConfig) -> gce_google_channel_config.GoogleChannelConfig: + """Post-rpc interceptor for update_google_channel_config + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_message_bus(self, request: eventarc.UpdateMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_message_bus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_message_bus + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_pipeline(self, request: eventarc.UpdatePipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdatePipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_pipeline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_pipeline + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_trigger(self, request: eventarc.UpdateTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_trigger + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc 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, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc 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, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc 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, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc 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 Eventarc server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EventarcRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EventarcRestInterceptor + + +class EventarcRestTransport(_BaseEventarcRestTransport): + """REST backend synchronous transport for Eventarc. + + Eventarc allows users to subscribe to various events that are + provided by Google Cloud services and forward them to supported + destinations. + + This 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 = 'eventarc.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[EventarcRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'eventarc.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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 EventarcRestInterceptor() + 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': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + '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 _CreateChannel(_BaseEventarcRestTransport._BaseCreateChannel, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreateChannel") + + @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: eventarc.CreateChannelRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create channel method over HTTP. + + Args: + request (~.eventarc.CreateChannelRequest): + The request object. The request message for the + CreateChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreateChannel._get_http_options() + request, metadata = self._interceptor.pre_create_channel(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreateChannel._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreateChannel._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateChannel._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreateChannel._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_channel(resp) + return resp + + class _CreateChannelConnection(_BaseEventarcRestTransport._BaseCreateChannelConnection, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreateChannelConnection") + + @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: eventarc.CreateChannelConnectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create channel connection method over HTTP. + + Args: + request (~.eventarc.CreateChannelConnectionRequest): + The request object. The request message for the + CreateChannelConnection method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_http_options() + request, metadata = self._interceptor.pre_create_channel_connection(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreateChannelConnection._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_channel_connection(resp) + return resp + + class _CreateEnrollment(_BaseEventarcRestTransport._BaseCreateEnrollment, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreateEnrollment") + + @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: eventarc.CreateEnrollmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create enrollment method over HTTP. + + Args: + request (~.eventarc.CreateEnrollmentRequest): + The request object. The request message for the + CreateEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreateEnrollment._get_http_options() + request, metadata = self._interceptor.pre_create_enrollment(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreateEnrollment._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreateEnrollment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateEnrollment._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreateEnrollment._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_enrollment(resp) + return resp + + class _CreateGoogleApiSource(_BaseEventarcRestTransport._BaseCreateGoogleApiSource, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreateGoogleApiSource") + + @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: eventarc.CreateGoogleApiSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create google api source method over HTTP. + + Args: + request (~.eventarc.CreateGoogleApiSourceRequest): + The request object. The request message for the + CreateGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_http_options() + request, metadata = self._interceptor.pre_create_google_api_source(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreateGoogleApiSource._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_google_api_source(resp) + return resp + + class _CreateMessageBus(_BaseEventarcRestTransport._BaseCreateMessageBus, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreateMessageBus") + + @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: eventarc.CreateMessageBusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create message bus method over HTTP. + + Args: + request (~.eventarc.CreateMessageBusRequest): + The request object. The request message for the + CreateMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreateMessageBus._get_http_options() + request, metadata = self._interceptor.pre_create_message_bus(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreateMessageBus._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreateMessageBus._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateMessageBus._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreateMessageBus._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_message_bus(resp) + return resp + + class _CreatePipeline(_BaseEventarcRestTransport._BaseCreatePipeline, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreatePipeline") + + @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: eventarc.CreatePipelineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create pipeline method over HTTP. + + Args: + request (~.eventarc.CreatePipelineRequest): + The request object. The request message for the + CreatePipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreatePipeline._get_http_options() + request, metadata = self._interceptor.pre_create_pipeline(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreatePipeline._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreatePipeline._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreatePipeline._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreatePipeline._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_pipeline(resp) + return resp + + class _CreateTrigger(_BaseEventarcRestTransport._BaseCreateTrigger, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.CreateTrigger") + + @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: eventarc.CreateTriggerRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create trigger method over HTTP. + + Args: + request (~.eventarc.CreateTriggerRequest): + The request object. The request message for the + CreateTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseCreateTrigger._get_http_options() + request, metadata = self._interceptor.pre_create_trigger(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCreateTrigger._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCreateTrigger._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateTrigger._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CreateTrigger._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_trigger(resp) + return resp + + class _DeleteChannel(_BaseEventarcRestTransport._BaseDeleteChannel, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeleteChannel") + + @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: eventarc.DeleteChannelRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete channel method over HTTP. + + Args: + request (~.eventarc.DeleteChannelRequest): + The request object. The request message for the + DeleteChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteChannel._get_http_options() + request, metadata = self._interceptor.pre_delete_channel(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannel._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteChannel._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeleteChannel._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_channel(resp) + return resp + + class _DeleteChannelConnection(_BaseEventarcRestTransport._BaseDeleteChannelConnection, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeleteChannelConnection") + + @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: eventarc.DeleteChannelConnectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete channel connection method over HTTP. + + Args: + request (~.eventarc.DeleteChannelConnectionRequest): + The request object. The request message for the + DeleteChannelConnection method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_http_options() + request, metadata = self._interceptor.pre_delete_channel_connection(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeleteChannelConnection._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_channel_connection(resp) + return resp + + class _DeleteEnrollment(_BaseEventarcRestTransport._BaseDeleteEnrollment, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeleteEnrollment") + + @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: eventarc.DeleteEnrollmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete enrollment method over HTTP. + + Args: + request (~.eventarc.DeleteEnrollmentRequest): + The request object. The request message for the + DeleteEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_http_options() + request, metadata = self._interceptor.pre_delete_enrollment(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeleteEnrollment._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_enrollment(resp) + return resp + + class _DeleteGoogleApiSource(_BaseEventarcRestTransport._BaseDeleteGoogleApiSource, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeleteGoogleApiSource") + + @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: eventarc.DeleteGoogleApiSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete google api source method over HTTP. + + Args: + request (~.eventarc.DeleteGoogleApiSourceRequest): + The request object. The request message for the + DeleteGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_http_options() + request, metadata = self._interceptor.pre_delete_google_api_source(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeleteGoogleApiSource._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_google_api_source(resp) + return resp + + class _DeleteMessageBus(_BaseEventarcRestTransport._BaseDeleteMessageBus, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeleteMessageBus") + + @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: eventarc.DeleteMessageBusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete message bus method over HTTP. + + Args: + request (~.eventarc.DeleteMessageBusRequest): + The request object. The request message for the + DeleteMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_http_options() + request, metadata = self._interceptor.pre_delete_message_bus(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeleteMessageBus._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_message_bus(resp) + return resp + + class _DeletePipeline(_BaseEventarcRestTransport._BaseDeletePipeline, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeletePipeline") + + @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: eventarc.DeletePipelineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete pipeline method over HTTP. + + Args: + request (~.eventarc.DeletePipelineRequest): + The request object. The request message for the + DeletePipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeletePipeline._get_http_options() + request, metadata = self._interceptor.pre_delete_pipeline(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeletePipeline._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeletePipeline._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeletePipeline._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_pipeline(resp) + return resp + + class _DeleteTrigger(_BaseEventarcRestTransport._BaseDeleteTrigger, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.DeleteTrigger") + + @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: eventarc.DeleteTriggerRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete trigger method over HTTP. + + Args: + request (~.eventarc.DeleteTriggerRequest): + The request object. The request message for the + DeleteTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteTrigger._get_http_options() + request, metadata = self._interceptor.pre_delete_trigger(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteTrigger._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteTrigger._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._DeleteTrigger._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_trigger(resp) + return resp + + class _GetChannel(_BaseEventarcRestTransport._BaseGetChannel, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetChannel") + + @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: eventarc.GetChannelRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> channel.Channel: + r"""Call the get channel method over HTTP. + + Args: + request (~.eventarc.GetChannelRequest): + The request object. The request message for the + GetChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.channel.Channel: + A representation of the Channel + resource. A Channel is a resource on + which event providers publish their + events. The published events are + delivered through the transport + associated with the channel. Note that a + channel is associated with exactly one + event provider. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetChannel._get_http_options() + request, metadata = self._interceptor.pre_get_channel(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetChannel._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetChannel._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetChannel._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 = channel.Channel() + pb_resp = channel.Channel.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_channel(resp) + return resp + + class _GetChannelConnection(_BaseEventarcRestTransport._BaseGetChannelConnection, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetChannelConnection") + + @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: eventarc.GetChannelConnectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> channel_connection.ChannelConnection: + r"""Call the get channel connection method over HTTP. + + Args: + request (~.eventarc.GetChannelConnectionRequest): + The request object. The request message for the + GetChannelConnection method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.channel_connection.ChannelConnection: + A representation of the + ChannelConnection resource. A + ChannelConnection is a resource which + event providers create during the + activation process to establish a + connection between the provider and the + subscriber channel. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetChannelConnection._get_http_options() + request, metadata = self._interceptor.pre_get_channel_connection(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetChannelConnection._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetChannelConnection._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetChannelConnection._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 = channel_connection.ChannelConnection() + pb_resp = channel_connection.ChannelConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_channel_connection(resp) + return resp + + class _GetEnrollment(_BaseEventarcRestTransport._BaseGetEnrollment, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetEnrollment") + + @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: eventarc.GetEnrollmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> enrollment.Enrollment: + r"""Call the get enrollment method over HTTP. + + Args: + request (~.eventarc.GetEnrollmentRequest): + The request object. The request message for the + GetEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.enrollment.Enrollment: + An enrollment represents a + subscription for messages on a + particular message bus. It defines a + matching criteria for messages on the + bus and the subscriber endpoint where + matched messages should be delivered. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetEnrollment._get_http_options() + request, metadata = self._interceptor.pre_get_enrollment(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetEnrollment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetEnrollment._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetEnrollment._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 = enrollment.Enrollment() + pb_resp = enrollment.Enrollment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_enrollment(resp) + return resp + + class _GetGoogleApiSource(_BaseEventarcRestTransport._BaseGetGoogleApiSource, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetGoogleApiSource") + + @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: eventarc.GetGoogleApiSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> google_api_source.GoogleApiSource: + r"""Call the get google api source method over HTTP. + + Args: + request (~.eventarc.GetGoogleApiSourceRequest): + The request object. The request message for the + GetGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.google_api_source.GoogleApiSource: + A GoogleApiSource represents a + subscription of 1P events from a + MessageBus. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_http_options() + request, metadata = self._interceptor.pre_get_google_api_source(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetGoogleApiSource._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 = google_api_source.GoogleApiSource() + pb_resp = google_api_source.GoogleApiSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_google_api_source(resp) + return resp + + class _GetGoogleChannelConfig(_BaseEventarcRestTransport._BaseGetGoogleChannelConfig, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetGoogleChannelConfig") + + @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: eventarc.GetGoogleChannelConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> google_channel_config.GoogleChannelConfig: + r"""Call the get google channel config method over HTTP. + + Args: + request (~.eventarc.GetGoogleChannelConfigRequest): + The request object. The request message for the + GetGoogleChannelConfig method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.google_channel_config.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_http_options() + request, metadata = self._interceptor.pre_get_google_channel_config(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetGoogleChannelConfig._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 = google_channel_config.GoogleChannelConfig() + pb_resp = google_channel_config.GoogleChannelConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_google_channel_config(resp) + return resp + + class _GetMessageBus(_BaseEventarcRestTransport._BaseGetMessageBus, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetMessageBus") + + @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: eventarc.GetMessageBusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> message_bus.MessageBus: + r"""Call the get message bus method over HTTP. + + Args: + request (~.eventarc.GetMessageBusRequest): + The request object. The request message for the + GetMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.message_bus.MessageBus: + MessageBus for the messages flowing + through the system. The admin has + visibility and control over the messages + being published and consumed and can + restrict publishers and subscribers to + only a subset of data available in the + system by defining authorization + policies. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetMessageBus._get_http_options() + request, metadata = self._interceptor.pre_get_message_bus(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetMessageBus._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetMessageBus._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetMessageBus._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 = message_bus.MessageBus() + pb_resp = message_bus.MessageBus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_message_bus(resp) + return resp + + class _GetPipeline(_BaseEventarcRestTransport._BaseGetPipeline, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetPipeline") + + @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: eventarc.GetPipelineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> pipeline.Pipeline: + r"""Call the get pipeline method over HTTP. + + Args: + request (~.eventarc.GetPipelineRequest): + The request object. The request message for the + GetPipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pipeline.Pipeline: + A representation of the Pipeline + resource. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetPipeline._get_http_options() + request, metadata = self._interceptor.pre_get_pipeline(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetPipeline._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetPipeline._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetPipeline._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 = pipeline.Pipeline() + pb_resp = pipeline.Pipeline.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_pipeline(resp) + return resp + + class _GetProvider(_BaseEventarcRestTransport._BaseGetProvider, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetProvider") + + @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: eventarc.GetProviderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> discovery.Provider: + r"""Call the get provider method over HTTP. + + Args: + request (~.eventarc.GetProviderRequest): + The request object. The request message for the + GetProvider method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.discovery.Provider: + A representation of the Provider + resource. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetProvider._get_http_options() + request, metadata = self._interceptor.pre_get_provider(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetProvider._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetProvider._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetProvider._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 = discovery.Provider() + pb_resp = discovery.Provider.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_provider(resp) + return resp + + class _GetTrigger(_BaseEventarcRestTransport._BaseGetTrigger, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetTrigger") + + @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: eventarc.GetTriggerRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> trigger.Trigger: + r"""Call the get trigger method over HTTP. + + Args: + request (~.eventarc.GetTriggerRequest): + The request object. The request message for the + GetTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.trigger.Trigger: + A representation of the trigger + resource. + + """ + + http_options = _BaseEventarcRestTransport._BaseGetTrigger._get_http_options() + request, metadata = self._interceptor.pre_get_trigger(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetTrigger._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetTrigger._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._GetTrigger._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 = trigger.Trigger() + pb_resp = trigger.Trigger.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_trigger(resp) + return resp + + class _ListChannelConnections(_BaseEventarcRestTransport._BaseListChannelConnections, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListChannelConnections") + + @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: eventarc.ListChannelConnectionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListChannelConnectionsResponse: + r"""Call the list channel connections method over HTTP. + + Args: + request (~.eventarc.ListChannelConnectionsRequest): + The request object. The request message for the + ListChannelConnections method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListChannelConnectionsResponse: + The response message for the ``ListChannelConnections`` + method. + + """ + + http_options = _BaseEventarcRestTransport._BaseListChannelConnections._get_http_options() + request, metadata = self._interceptor.pre_list_channel_connections(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListChannelConnections._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListChannelConnections._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListChannelConnections._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 = eventarc.ListChannelConnectionsResponse() + pb_resp = eventarc.ListChannelConnectionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_channel_connections(resp) + return resp + + class _ListChannels(_BaseEventarcRestTransport._BaseListChannels, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListChannels") + + @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: eventarc.ListChannelsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListChannelsResponse: + r"""Call the list channels method over HTTP. + + Args: + request (~.eventarc.ListChannelsRequest): + The request object. The request message for the + ListChannels method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListChannelsResponse: + The response message for the ``ListChannels`` method. + """ + + http_options = _BaseEventarcRestTransport._BaseListChannels._get_http_options() + request, metadata = self._interceptor.pre_list_channels(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListChannels._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListChannels._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListChannels._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 = eventarc.ListChannelsResponse() + pb_resp = eventarc.ListChannelsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_channels(resp) + return resp + + class _ListEnrollments(_BaseEventarcRestTransport._BaseListEnrollments, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListEnrollments") + + @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: eventarc.ListEnrollmentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListEnrollmentsResponse: + r"""Call the list enrollments method over HTTP. + + Args: + request (~.eventarc.ListEnrollmentsRequest): + The request object. The request message for the + ListEnrollments method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListEnrollmentsResponse: + The response message for the ``ListEnrollments`` method. + """ + + http_options = _BaseEventarcRestTransport._BaseListEnrollments._get_http_options() + request, metadata = self._interceptor.pre_list_enrollments(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListEnrollments._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListEnrollments._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListEnrollments._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 = eventarc.ListEnrollmentsResponse() + pb_resp = eventarc.ListEnrollmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_enrollments(resp) + return resp + + class _ListGoogleApiSources(_BaseEventarcRestTransport._BaseListGoogleApiSources, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListGoogleApiSources") + + @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: eventarc.ListGoogleApiSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListGoogleApiSourcesResponse: + r"""Call the list google api sources method over HTTP. + + Args: + request (~.eventarc.ListGoogleApiSourcesRequest): + The request object. The request message for the + ListGoogleApiSources method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListGoogleApiSourcesResponse: + The response message for the ``ListGoogleApiSources`` + method. + + """ + + http_options = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_http_options() + request, metadata = self._interceptor.pre_list_google_api_sources(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListGoogleApiSources._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 = eventarc.ListGoogleApiSourcesResponse() + pb_resp = eventarc.ListGoogleApiSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_google_api_sources(resp) + return resp + + class _ListMessageBusEnrollments(_BaseEventarcRestTransport._BaseListMessageBusEnrollments, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListMessageBusEnrollments") + + @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: eventarc.ListMessageBusEnrollmentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListMessageBusEnrollmentsResponse: + r"""Call the list message bus + enrollments method over HTTP. + + Args: + request (~.eventarc.ListMessageBusEnrollmentsRequest): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListMessageBusEnrollmentsResponse: + The response message for the + ``ListMessageBusEnrollments`` method.\` + + """ + + http_options = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_http_options() + request, metadata = self._interceptor.pre_list_message_bus_enrollments(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListMessageBusEnrollments._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 = eventarc.ListMessageBusEnrollmentsResponse() + pb_resp = eventarc.ListMessageBusEnrollmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_message_bus_enrollments(resp) + return resp + + class _ListMessageBuses(_BaseEventarcRestTransport._BaseListMessageBuses, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListMessageBuses") + + @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: eventarc.ListMessageBusesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListMessageBusesResponse: + r"""Call the list message buses method over HTTP. + + Args: + request (~.eventarc.ListMessageBusesRequest): + The request object. The request message for the + ListMessageBuses method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListMessageBusesResponse: + The response message for the ``ListMessageBuses`` + method. + + """ + + http_options = _BaseEventarcRestTransport._BaseListMessageBuses._get_http_options() + request, metadata = self._interceptor.pre_list_message_buses(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListMessageBuses._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListMessageBuses._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListMessageBuses._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 = eventarc.ListMessageBusesResponse() + pb_resp = eventarc.ListMessageBusesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_message_buses(resp) + return resp + + class _ListPipelines(_BaseEventarcRestTransport._BaseListPipelines, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListPipelines") + + @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: eventarc.ListPipelinesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListPipelinesResponse: + r"""Call the list pipelines method over HTTP. + + Args: + request (~.eventarc.ListPipelinesRequest): + The request object. The request message for the + ListPipelines method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListPipelinesResponse: + The response message for the + ListPipelines method. + + """ + + http_options = _BaseEventarcRestTransport._BaseListPipelines._get_http_options() + request, metadata = self._interceptor.pre_list_pipelines(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListPipelines._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListPipelines._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListPipelines._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 = eventarc.ListPipelinesResponse() + pb_resp = eventarc.ListPipelinesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_pipelines(resp) + return resp + + class _ListProviders(_BaseEventarcRestTransport._BaseListProviders, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListProviders") + + @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: eventarc.ListProvidersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListProvidersResponse: + r"""Call the list providers method over HTTP. + + Args: + request (~.eventarc.ListProvidersRequest): + The request object. The request message for the + ListProviders method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListProvidersResponse: + The response message for the ``ListProviders`` method. + """ + + http_options = _BaseEventarcRestTransport._BaseListProviders._get_http_options() + request, metadata = self._interceptor.pre_list_providers(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListProviders._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListProviders._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListProviders._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 = eventarc.ListProvidersResponse() + pb_resp = eventarc.ListProvidersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_providers(resp) + return resp + + class _ListTriggers(_BaseEventarcRestTransport._BaseListTriggers, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.ListTriggers") + + @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: eventarc.ListTriggersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> eventarc.ListTriggersResponse: + r"""Call the list triggers method over HTTP. + + Args: + request (~.eventarc.ListTriggersRequest): + The request object. The request message for the + ListTriggers method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.eventarc.ListTriggersResponse: + The response message for the ``ListTriggers`` method. + """ + + http_options = _BaseEventarcRestTransport._BaseListTriggers._get_http_options() + request, metadata = self._interceptor.pre_list_triggers(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListTriggers._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListTriggers._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._ListTriggers._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 = eventarc.ListTriggersResponse() + pb_resp = eventarc.ListTriggersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_triggers(resp) + return resp + + class _UpdateChannel(_BaseEventarcRestTransport._BaseUpdateChannel, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdateChannel") + + @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: eventarc.UpdateChannelRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update channel method over HTTP. + + Args: + request (~.eventarc.UpdateChannelRequest): + The request object. The request message for the + UpdateChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdateChannel._get_http_options() + request, metadata = self._interceptor.pre_update_channel(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateChannel._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdateChannel._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdateChannel._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdateChannel._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_update_channel(resp) + return resp + + class _UpdateEnrollment(_BaseEventarcRestTransport._BaseUpdateEnrollment, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdateEnrollment") + + @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: eventarc.UpdateEnrollmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update enrollment method over HTTP. + + Args: + request (~.eventarc.UpdateEnrollmentRequest): + The request object. The request message for the + UpdateEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_http_options() + request, metadata = self._interceptor.pre_update_enrollment(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdateEnrollment._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_update_enrollment(resp) + return resp + + class _UpdateGoogleApiSource(_BaseEventarcRestTransport._BaseUpdateGoogleApiSource, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdateGoogleApiSource") + + @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: eventarc.UpdateGoogleApiSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update google api source method over HTTP. + + Args: + request (~.eventarc.UpdateGoogleApiSourceRequest): + The request object. The request message for the + UpdateGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_http_options() + request, metadata = self._interceptor.pre_update_google_api_source(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdateGoogleApiSource._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_update_google_api_source(resp) + return resp + + class _UpdateGoogleChannelConfig(_BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdateGoogleChannelConfig") + + @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: eventarc.UpdateGoogleChannelConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gce_google_channel_config.GoogleChannelConfig: + r"""Call the update google channel + config method over HTTP. + + Args: + request (~.eventarc.UpdateGoogleChannelConfigRequest): + The request object. The request message for the + UpdateGoogleChannelConfig method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gce_google_channel_config.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_http_options() + request, metadata = self._interceptor.pre_update_google_channel_config(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdateGoogleChannelConfig._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 = gce_google_channel_config.GoogleChannelConfig() + pb_resp = gce_google_channel_config.GoogleChannelConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_google_channel_config(resp) + return resp + + class _UpdateMessageBus(_BaseEventarcRestTransport._BaseUpdateMessageBus, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdateMessageBus") + + @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: eventarc.UpdateMessageBusRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update message bus method over HTTP. + + Args: + request (~.eventarc.UpdateMessageBusRequest): + The request object. The request message for the + UpdateMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_http_options() + request, metadata = self._interceptor.pre_update_message_bus(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdateMessageBus._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_update_message_bus(resp) + return resp + + class _UpdatePipeline(_BaseEventarcRestTransport._BaseUpdatePipeline, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdatePipeline") + + @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: eventarc.UpdatePipelineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update pipeline method over HTTP. + + Args: + request (~.eventarc.UpdatePipelineRequest): + The request object. The request message for the + UpdatePipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdatePipeline._get_http_options() + request, metadata = self._interceptor.pre_update_pipeline(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdatePipeline._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdatePipeline._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdatePipeline._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdatePipeline._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_update_pipeline(resp) + return resp + + class _UpdateTrigger(_BaseEventarcRestTransport._BaseUpdateTrigger, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.UpdateTrigger") + + @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: eventarc.UpdateTriggerRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update trigger method over HTTP. + + Args: + request (~.eventarc.UpdateTriggerRequest): + The request object. The request message for the + UpdateTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEventarcRestTransport._BaseUpdateTrigger._get_http_options() + request, metadata = self._interceptor.pre_update_trigger(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateTrigger._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseUpdateTrigger._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseUpdateTrigger._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._UpdateTrigger._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_update_trigger(resp) + return resp + + @property + def create_channel_(self) -> Callable[ + [eventarc.CreateChannelRequest], + 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._CreateChannel(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_channel_connection(self) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + 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._CreateChannelConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_enrollment(self) -> Callable[ + [eventarc.CreateEnrollmentRequest], + 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._CreateEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_google_api_source(self) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + 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._CreateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_message_bus(self) -> Callable[ + [eventarc.CreateMessageBusRequest], + 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._CreateMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_pipeline(self) -> Callable[ + [eventarc.CreatePipelineRequest], + 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._CreatePipeline(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_trigger(self) -> Callable[ + [eventarc.CreateTriggerRequest], + 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._CreateTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_channel(self) -> Callable[ + [eventarc.DeleteChannelRequest], + 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._DeleteChannel(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_channel_connection(self) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + 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._DeleteChannelConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_enrollment(self) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + 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._DeleteEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_google_api_source(self) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + 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._DeleteGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_message_bus(self) -> Callable[ + [eventarc.DeleteMessageBusRequest], + 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._DeleteMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_pipeline(self) -> Callable[ + [eventarc.DeletePipelineRequest], + 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._DeletePipeline(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_trigger(self) -> Callable[ + [eventarc.DeleteTriggerRequest], + 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._DeleteTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_channel(self) -> Callable[ + [eventarc.GetChannelRequest], + channel.Channel]: + # 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._GetChannel(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_channel_connection(self) -> Callable[ + [eventarc.GetChannelConnectionRequest], + channel_connection.ChannelConnection]: + # 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._GetChannelConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_enrollment(self) -> Callable[ + [eventarc.GetEnrollmentRequest], + enrollment.Enrollment]: + # 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._GetEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_google_api_source(self) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + google_api_source.GoogleApiSource]: + # 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._GetGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_google_channel_config(self) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + google_channel_config.GoogleChannelConfig]: + # 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._GetGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_message_bus(self) -> Callable[ + [eventarc.GetMessageBusRequest], + message_bus.MessageBus]: + # 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._GetMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_pipeline(self) -> Callable[ + [eventarc.GetPipelineRequest], + pipeline.Pipeline]: + # 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._GetPipeline(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_provider(self) -> Callable[ + [eventarc.GetProviderRequest], + discovery.Provider]: + # 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._GetProvider(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_trigger(self) -> Callable[ + [eventarc.GetTriggerRequest], + trigger.Trigger]: + # 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._GetTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_channel_connections(self) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + eventarc.ListChannelConnectionsResponse]: + # 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._ListChannelConnections(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_channels(self) -> Callable[ + [eventarc.ListChannelsRequest], + eventarc.ListChannelsResponse]: + # 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._ListChannels(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_enrollments(self) -> Callable[ + [eventarc.ListEnrollmentsRequest], + eventarc.ListEnrollmentsResponse]: + # 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._ListEnrollments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_google_api_sources(self) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + eventarc.ListGoogleApiSourcesResponse]: + # 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._ListGoogleApiSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_message_bus_enrollments(self) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse]: + # 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._ListMessageBusEnrollments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_message_buses(self) -> Callable[ + [eventarc.ListMessageBusesRequest], + eventarc.ListMessageBusesResponse]: + # 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._ListMessageBuses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_pipelines(self) -> Callable[ + [eventarc.ListPipelinesRequest], + eventarc.ListPipelinesResponse]: + # 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._ListPipelines(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_providers(self) -> Callable[ + [eventarc.ListProvidersRequest], + eventarc.ListProvidersResponse]: + # 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._ListProviders(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_triggers(self) -> Callable[ + [eventarc.ListTriggersRequest], + eventarc.ListTriggersResponse]: + # 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._ListTriggers(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_channel(self) -> Callable[ + [eventarc.UpdateChannelRequest], + 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._UpdateChannel(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_enrollment(self) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + 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._UpdateEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_google_api_source(self) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + 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._UpdateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_google_channel_config(self) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + gce_google_channel_config.GoogleChannelConfig]: + # 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._UpdateGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_message_bus(self) -> Callable[ + [eventarc.UpdateMessageBusRequest], + 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._UpdateMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_pipeline(self) -> Callable[ + [eventarc.UpdatePipelineRequest], + 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._UpdatePipeline(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_trigger(self) -> Callable[ + [eventarc.UpdateTriggerRequest], + 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._UpdateTrigger(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(_BaseEventarcRestTransport._BaseGetLocation, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseEventarcRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseEventarcRestTransport._BaseListLocations, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseEventarcRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseEventarcRestTransport._BaseGetIamPolicy, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseEventarcRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseEventarcRestTransport._BaseSetIamPolicy, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseEventarcRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseEventarcRestTransport._BaseTestIamPermissions, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseEventarcRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseEventarcRestTransport._BaseCancelOperation, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options = _BaseEventarcRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseEventarcRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._CancelOperation._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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseEventarcRestTransport._BaseDeleteOperation, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options = _BaseEventarcRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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(_BaseEventarcRestTransport._BaseGetOperation, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseEventarcRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseEventarcRestTransport._BaseListOperations, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.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, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseEventarcRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseEventarcRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + # Send the request + response = EventarcRestTransport._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) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EventarcRestTransport', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py new file mode 100644 index 000000000000..09c44e75071f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py @@ -0,0 +1,1996 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import EventarcTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseEventarcRestTransport(EventarcTransport): + """Base REST backend transport for Eventarc. + + 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 = 'eventarc.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: 'eventarc.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 _BaseCreateChannel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "channelId" : "", } + + @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/*}/channels', + 'body': 'channel', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateChannelRequest.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(_BaseEventarcRestTransport._BaseCreateChannel._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateChannelConnection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "channelConnectionId" : "", } + + @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/*}/channelConnections', + 'body': 'channel_connection', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateChannelConnectionRequest.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(_BaseEventarcRestTransport._BaseCreateChannelConnection._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateEnrollment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "enrollmentId" : "", } + + @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/*}/enrollments', + 'body': 'enrollment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateEnrollmentRequest.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(_BaseEventarcRestTransport._BaseCreateEnrollment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateGoogleApiSource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "googleApiSourceId" : "", } + + @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/*}/googleApiSources', + 'body': 'google_api_source', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateMessageBus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "messageBusId" : "", } + + @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/*}/messageBuses', + 'body': 'message_bus', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateMessageBusRequest.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(_BaseEventarcRestTransport._BaseCreateMessageBus._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreatePipeline: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "pipelineId" : "", } + + @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/*}/pipelines', + 'body': 'pipeline', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreatePipelineRequest.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(_BaseEventarcRestTransport._BaseCreatePipeline._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateTrigger: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "triggerId" : "", } + + @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/*}/triggers', + 'body': 'trigger', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateTriggerRequest.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(_BaseEventarcRestTransport._BaseCreateTrigger._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteChannel: + 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/*/channels/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteChannelRequest.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(_BaseEventarcRestTransport._BaseDeleteChannel._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteChannelConnection: + 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/*/channelConnections/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteChannelConnectionRequest.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(_BaseEventarcRestTransport._BaseDeleteChannelConnection._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEnrollment: + 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/*/enrollments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteEnrollmentRequest.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(_BaseEventarcRestTransport._BaseDeleteEnrollment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteGoogleApiSource: + 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/*/googleApiSources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMessageBus: + 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/*/messageBuses/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteMessageBusRequest.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(_BaseEventarcRestTransport._BaseDeleteMessageBus._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePipeline: + 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/*/pipelines/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeletePipelineRequest.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(_BaseEventarcRestTransport._BaseDeletePipeline._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTrigger: + 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/*/triggers/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteTriggerRequest.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(_BaseEventarcRestTransport._BaseDeleteTrigger._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetChannel: + 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/*/channels/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetChannelRequest.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(_BaseEventarcRestTransport._BaseGetChannel._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetChannelConnection: + 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/*/channelConnections/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetChannelConnectionRequest.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(_BaseEventarcRestTransport._BaseGetChannelConnection._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEnrollment: + 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/*/enrollments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetEnrollmentRequest.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(_BaseEventarcRestTransport._BaseGetEnrollment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGoogleApiSource: + 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/*/googleApiSources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseGetGoogleApiSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGoogleChannelConfig: + 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/*/googleChannelConfig}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetGoogleChannelConfigRequest.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(_BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMessageBus: + 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/*/messageBuses/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetMessageBusRequest.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(_BaseEventarcRestTransport._BaseGetMessageBus._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPipeline: + 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/*/pipelines/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetPipelineRequest.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(_BaseEventarcRestTransport._BaseGetPipeline._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProvider: + 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/*/providers/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetProviderRequest.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(_BaseEventarcRestTransport._BaseGetProvider._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTrigger: + 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/*/triggers/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetTriggerRequest.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(_BaseEventarcRestTransport._BaseGetTrigger._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListChannelConnections: + 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/*}/channelConnections', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListChannelConnectionsRequest.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(_BaseEventarcRestTransport._BaseListChannelConnections._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListChannels: + 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/*}/channels', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListChannelsRequest.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(_BaseEventarcRestTransport._BaseListChannels._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEnrollments: + 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/*}/enrollments', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListEnrollmentsRequest.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(_BaseEventarcRestTransport._BaseListEnrollments._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGoogleApiSources: + 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/*}/googleApiSources', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListGoogleApiSourcesRequest.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(_BaseEventarcRestTransport._BaseListGoogleApiSources._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMessageBusEnrollments: + 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/*/messageBuses/*}:listEnrollments', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListMessageBusEnrollmentsRequest.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(_BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMessageBuses: + 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/*}/messageBuses', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListMessageBusesRequest.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(_BaseEventarcRestTransport._BaseListMessageBuses._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPipelines: + 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/*}/pipelines', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListPipelinesRequest.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(_BaseEventarcRestTransport._BaseListPipelines._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListProviders: + 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/*}/providers', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListProvidersRequest.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(_BaseEventarcRestTransport._BaseListProviders._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTriggers: + 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/*}/triggers', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.ListTriggersRequest.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(_BaseEventarcRestTransport._BaseListTriggers._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateChannel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{channel.name=projects/*/locations/*/channels/*}', + 'body': 'channel', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateChannelRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEnrollment: + 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': '/v1/{enrollment.name=projects/*/locations/*/enrollments/*}', + 'body': 'enrollment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateEnrollmentRequest.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(_BaseEventarcRestTransport._BaseUpdateEnrollment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGoogleApiSource: + 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': '/v1/{google_api_source.name=projects/*/locations/*/googleApiSources/*}', + 'body': 'google_api_source', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGoogleChannelConfig: + 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': '/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}', + 'body': 'google_channel_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateGoogleChannelConfigRequest.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(_BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateMessageBus: + 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': '/v1/{message_bus.name=projects/*/locations/*/messageBuses/*}', + 'body': 'message_bus', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateMessageBusRequest.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(_BaseEventarcRestTransport._BaseUpdateMessageBus._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePipeline: + 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': '/v1/{pipeline.name=projects/*/locations/*/pipelines/*}', + 'body': 'pipeline', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdatePipelineRequest.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(_BaseEventarcRestTransport._BaseUpdatePipeline._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTrigger: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{trigger.name=projects/*/locations/*/triggers/*}', + 'body': 'trigger', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateTriggerRequest.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["$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/*/triggers/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/channels/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/channelConnections/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/messageBuses/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/enrollments/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/pipelines/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/googleApiSources/*}: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/*/triggers/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/channels/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/channelConnections/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/messageBuses/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/enrollments/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/pipelines/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/googleApiSources/*}: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/*/triggers/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/channels/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/channelConnections/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/messageBuses/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/enrollments/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/pipelines/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/googleApiSources/*}: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 _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': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + '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 _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': '/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 + + 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 + + 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': '/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__=( + '_BaseEventarcRestTransport', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py new file mode 100644 index 000000000000..010c3974f234 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .channel import ( + Channel, +) +from .channel_connection import ( + ChannelConnection, +) +from .discovery import ( + EventType, + FilteringAttribute, + Provider, +) +from .enrollment import ( + Enrollment, +) +from .eventarc import ( + CreateChannelConnectionRequest, + CreateChannelRequest, + CreateEnrollmentRequest, + CreateGoogleApiSourceRequest, + CreateMessageBusRequest, + CreatePipelineRequest, + CreateTriggerRequest, + DeleteChannelConnectionRequest, + DeleteChannelRequest, + DeleteEnrollmentRequest, + DeleteGoogleApiSourceRequest, + DeleteMessageBusRequest, + DeletePipelineRequest, + DeleteTriggerRequest, + GetChannelConnectionRequest, + GetChannelRequest, + GetEnrollmentRequest, + GetGoogleApiSourceRequest, + GetGoogleChannelConfigRequest, + GetMessageBusRequest, + GetPipelineRequest, + GetProviderRequest, + GetTriggerRequest, + ListChannelConnectionsRequest, + ListChannelConnectionsResponse, + ListChannelsRequest, + ListChannelsResponse, + ListEnrollmentsRequest, + ListEnrollmentsResponse, + ListGoogleApiSourcesRequest, + ListGoogleApiSourcesResponse, + ListMessageBusEnrollmentsRequest, + ListMessageBusEnrollmentsResponse, + ListMessageBusesRequest, + ListMessageBusesResponse, + ListPipelinesRequest, + ListPipelinesResponse, + ListProvidersRequest, + ListProvidersResponse, + ListTriggersRequest, + ListTriggersResponse, + OperationMetadata, + UpdateChannelRequest, + UpdateEnrollmentRequest, + UpdateGoogleApiSourceRequest, + UpdateGoogleChannelConfigRequest, + UpdateMessageBusRequest, + UpdatePipelineRequest, + UpdateTriggerRequest, +) +from .google_api_source import ( + GoogleApiSource, +) +from .google_channel_config import ( + GoogleChannelConfig, +) +from .logging_config import ( + LoggingConfig, +) +from .message_bus import ( + MessageBus, +) +from .network_config import ( + NetworkConfig, +) +from .pipeline import ( + Pipeline, +) +from .trigger import ( + CloudRun, + Destination, + EventFilter, + GKE, + HttpEndpoint, + Pubsub, + StateCondition, + Transport, + Trigger, +) + +__all__ = ( + 'Channel', + 'ChannelConnection', + 'EventType', + 'FilteringAttribute', + 'Provider', + 'Enrollment', + 'CreateChannelConnectionRequest', + 'CreateChannelRequest', + 'CreateEnrollmentRequest', + 'CreateGoogleApiSourceRequest', + 'CreateMessageBusRequest', + 'CreatePipelineRequest', + 'CreateTriggerRequest', + 'DeleteChannelConnectionRequest', + 'DeleteChannelRequest', + 'DeleteEnrollmentRequest', + 'DeleteGoogleApiSourceRequest', + 'DeleteMessageBusRequest', + 'DeletePipelineRequest', + 'DeleteTriggerRequest', + 'GetChannelConnectionRequest', + 'GetChannelRequest', + 'GetEnrollmentRequest', + 'GetGoogleApiSourceRequest', + 'GetGoogleChannelConfigRequest', + 'GetMessageBusRequest', + 'GetPipelineRequest', + 'GetProviderRequest', + 'GetTriggerRequest', + 'ListChannelConnectionsRequest', + 'ListChannelConnectionsResponse', + 'ListChannelsRequest', + 'ListChannelsResponse', + 'ListEnrollmentsRequest', + 'ListEnrollmentsResponse', + 'ListGoogleApiSourcesRequest', + 'ListGoogleApiSourcesResponse', + 'ListMessageBusEnrollmentsRequest', + 'ListMessageBusEnrollmentsResponse', + 'ListMessageBusesRequest', + 'ListMessageBusesResponse', + 'ListPipelinesRequest', + 'ListPipelinesResponse', + 'ListProvidersRequest', + 'ListProvidersResponse', + 'ListTriggersRequest', + 'ListTriggersResponse', + 'OperationMetadata', + 'UpdateChannelRequest', + 'UpdateEnrollmentRequest', + 'UpdateGoogleApiSourceRequest', + 'UpdateGoogleChannelConfigRequest', + 'UpdateMessageBusRequest', + 'UpdatePipelineRequest', + 'UpdateTriggerRequest', + 'GoogleApiSource', + 'GoogleChannelConfig', + 'LoggingConfig', + 'MessageBus', + 'NetworkConfig', + 'Pipeline', + 'CloudRun', + 'Destination', + 'EventFilter', + 'GKE', + 'HttpEndpoint', + 'Pubsub', + 'StateCondition', + 'Transport', + 'Trigger', +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py new file mode 100644 index 000000000000..811438b887b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'Channel', + }, +) + + +class Channel(proto.Message): + r"""A representation of the Channel resource. + A Channel is a resource on which event providers publish their + events. The published events are delivered through the transport + associated with the channel. Note that a channel is associated + with exactly one event provider. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The resource name of the channel. Must be unique + within the location on the project and must be in + ``projects/{project}/locations/{location}/channels/{channel_id}`` + format. + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + 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. + provider (str): + The name of the event provider (e.g. Eventarc SaaS partner) + associated with the channel. This provider will be granted + permissions to publish events to the channel. Format: + ``projects/{project}/locations/{location}/providers/{provider_id}``. + pubsub_topic (str): + Output only. The name of the Pub/Sub topic created and + managed by Eventarc system as a transport for the event + delivery. Format: ``projects/{project}/topics/{topic_id}``. + + This field is a member of `oneof`_ ``transport``. + state (google.cloud.eventarc_v1.types.Channel.State): + Output only. The state of a Channel. + activation_token (str): + Output only. The activation token for the + channel. The token must be used by the provider + to register the channel for publishing. + crypto_key_name (str): + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt their event data. + + It must match the pattern + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + satisfies_pzs (bool): + Output only. Whether or not this Channel + satisfies the requirements of physical zone + separation + """ + class State(proto.Enum): + r"""State lists all the possible states of a Channel + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + PENDING (1): + The PENDING state indicates that a Channel + has been created successfully and there is a new + activation token available for the subscriber to + use to convey the Channel to the provider in + order to create a Connection. + ACTIVE (2): + The ACTIVE state indicates that a Channel has + been successfully connected with the event + provider. An ACTIVE Channel is ready to receive + and route events from the event provider. + INACTIVE (3): + The INACTIVE state indicates that the Channel + cannot receive events permanently. There are two + possible cases this state can happen: + + 1. The SaaS provider disconnected from this + Channel. + 2. The Channel activation token has expired but + the SaaS provider wasn't connected. + + To re-establish a Connection with a provider, + the subscriber should create a new Channel and + give it to the provider. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + ACTIVE = 2 + INACTIVE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + provider: str = proto.Field( + proto.STRING, + number=7, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=8, + oneof='transport', + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + activation_token: str = proto.Field( + proto.STRING, + number=10, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=11, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=12, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py new file mode 100644 index 000000000000..59d79edf4331 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'ChannelConnection', + }, +) + + +class ChannelConnection(proto.Message): + r"""A representation of the ChannelConnection resource. + A ChannelConnection is a resource which event providers create + during the activation process to establish a connection between + the provider and the subscriber channel. + + Attributes: + name (str): + Required. The name of the connection. + uid (str): + Output only. Server assigned ID of the + resource. The server guarantees uniqueness and + immutability until deleted. + channel (str): + Required. The name of the connected subscriber Channel. This + is a weak reference to avoid cross project and cross + accounts references. This must be in + ``projects/{project}/location/{location}/channels/{channel_id}`` + format. + 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. + activation_token (str): + Input only. Activation token for the channel. + The token will be used during the creation of + ChannelConnection to bind the channel with the + provider project. This field will not be stored + in the provider resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + channel: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + activation_token: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py new file mode 100644 index 000000000000..d8424067300d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.eventarc.v1', + manifest={ + 'Provider', + 'EventType', + 'FilteringAttribute', + }, +) + + +class Provider(proto.Message): + r"""A representation of the Provider resource. + + Attributes: + name (str): + Output only. In + ``projects/{project}/locations/{location}/providers/{provider_id}`` + format. + display_name (str): + Output only. Human friendly name for the + Provider. For example "Cloud Storage". + event_types (MutableSequence[google.cloud.eventarc_v1.types.EventType]): + Output only. Event types for this provider. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + event_types: MutableSequence['EventType'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='EventType', + ) + + +class EventType(proto.Message): + r"""A representation of the event type resource. + + Attributes: + type_ (str): + Output only. The full name of the event type + (for example, + "google.cloud.storage.object.v1.finalized"). In + the form of + {provider-specific-prefix}.{resource}.{version}.{verb}. + Types MUST be versioned and event schemas are + guaranteed to remain backward compatible within + one version. Note that event type versions and + API versions do not need to match. + description (str): + Output only. Human friendly description of + what the event type is about. For example + "Bucket created in Cloud Storage". + filtering_attributes (MutableSequence[google.cloud.eventarc_v1.types.FilteringAttribute]): + Output only. Filtering attributes for the + event type. + event_schema_uri (str): + Output only. URI for the event schema. + For example + "https://github.com/googleapis/google-cloudevents/blob/master/proto/google/events/cloud/storage/v1/events.proto". + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filtering_attributes: MutableSequence['FilteringAttribute'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FilteringAttribute', + ) + event_schema_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +class FilteringAttribute(proto.Message): + r"""A representation of the FilteringAttribute resource. + Filtering attributes are per event type. + + Attributes: + attribute (str): + Output only. Attribute used for filtering the + event type. + description (str): + Output only. Description of the purpose of + the attribute. + required (bool): + Output only. If true, the triggers for this + provider should always specify a filter on these + attributes. Trigger creation will fail + otherwise. + path_pattern_supported (bool): + Output only. If true, the attribute accepts + matching expressions in the Eventarc PathPattern + format. + """ + + attribute: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + required: bool = proto.Field( + proto.BOOL, + number=3, + ) + path_pattern_supported: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py new file mode 100644 index 000000000000..86d09339e35a --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'Enrollment', + }, +) + + +class Enrollment(proto.Message): + r"""An enrollment represents a subscription for messages on a + particular message bus. It defines a matching criteria for + messages on the bus and the subscriber endpoint where matched + messages should be delivered. + + Attributes: + name (str): + Identifier. Resource name of the form + projects/{project}/locations/{location}/enrollments/{enrollment} + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on update and delete requests + to ensure that the client has an up-to-date + value before proceeding. + 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. + labels (MutableMapping[str, str]): + Optional. Resource labels. + annotations (MutableMapping[str, str]): + Optional. Resource annotations. + display_name (str): + Optional. Resource display name. + cel_match (str): + Required. A CEL expression identifying which + messages this enrollment applies to. + message_bus (str): + Required. Resource name of the message bus + identifying the source of the messages. It + matches the form + projects/{project}/locations/{location}/messageBuses/{messageBus}. + destination (str): + Required. Destination is the Pipeline that the Enrollment is + delivering to. It must point to the full resource name of a + Pipeline. Format: + "projects/{PROJECT_ID}/locations/{region}/pipelines/{PIPELINE_ID)". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + cel_match: str = proto.Field( + proto.STRING, + number=9, + ) + message_bus: str = proto.Field( + proto.STRING, + number=10, + ) + destination: str = proto.Field( + proto.STRING, + number=11, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py new file mode 100644 index 000000000000..7b3ef6ea4225 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py @@ -0,0 +1,1745 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.eventarc_v1.types import channel as gce_channel +from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline +from google.cloud.eventarc_v1.types import trigger as gce_trigger +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'GetTriggerRequest', + 'ListTriggersRequest', + 'ListTriggersResponse', + 'CreateTriggerRequest', + 'UpdateTriggerRequest', + 'DeleteTriggerRequest', + 'GetChannelRequest', + 'ListChannelsRequest', + 'ListChannelsResponse', + 'CreateChannelRequest', + 'UpdateChannelRequest', + 'DeleteChannelRequest', + 'GetProviderRequest', + 'ListProvidersRequest', + 'ListProvidersResponse', + 'GetChannelConnectionRequest', + 'ListChannelConnectionsRequest', + 'ListChannelConnectionsResponse', + 'CreateChannelConnectionRequest', + 'DeleteChannelConnectionRequest', + 'UpdateGoogleChannelConfigRequest', + 'GetGoogleChannelConfigRequest', + 'GetMessageBusRequest', + 'ListMessageBusesRequest', + 'ListMessageBusesResponse', + 'ListMessageBusEnrollmentsRequest', + 'ListMessageBusEnrollmentsResponse', + 'CreateMessageBusRequest', + 'UpdateMessageBusRequest', + 'DeleteMessageBusRequest', + 'GetEnrollmentRequest', + 'ListEnrollmentsRequest', + 'ListEnrollmentsResponse', + 'CreateEnrollmentRequest', + 'UpdateEnrollmentRequest', + 'DeleteEnrollmentRequest', + 'GetPipelineRequest', + 'ListPipelinesRequest', + 'ListPipelinesResponse', + 'CreatePipelineRequest', + 'UpdatePipelineRequest', + 'DeletePipelineRequest', + 'GetGoogleApiSourceRequest', + 'ListGoogleApiSourcesRequest', + 'ListGoogleApiSourcesResponse', + 'CreateGoogleApiSourceRequest', + 'UpdateGoogleApiSourceRequest', + 'DeleteGoogleApiSourceRequest', + 'OperationMetadata', + }, +) + + +class GetTriggerRequest(proto.Message): + r"""The request message for the GetTrigger method. + + Attributes: + name (str): + Required. The name of the trigger to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListTriggersRequest(proto.Message): + r"""The request message for the ListTriggers method. + + Attributes: + parent (str): + Required. The parent collection to list + triggers on. + page_size (int): + The maximum number of triggers to return on + each page. + Note: The service may send fewer. + page_token (str): + The page token; provide the value from the + ``next_page_token`` field in a previous ``ListTriggers`` + call to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListTriggers`` must match the call that provided the page + token. + order_by (str): + The sorting order of the resources returned. Value should be + a comma-separated list of fields. The default sorting order + is ascending. To specify descending order for a field, + append a ``desc`` suffix; for example: + ``name desc, trigger_id``. + filter (str): + Filter field. Used to filter the Triggers to + be listed. Possible filters are described in + https://google.aip.dev/160. For example, using + "?filter=destination:gke" would list only + Triggers with a gke destination. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListTriggersResponse(proto.Message): + r"""The response message for the ``ListTriggers`` method. + + Attributes: + triggers (MutableSequence[google.cloud.eventarc_v1.types.Trigger]): + The requested triggers, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListTriggers`` to request + the next page. If this is empty, then there are no more + pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + triggers: MutableSequence[gce_trigger.Trigger] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_trigger.Trigger, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateTriggerRequest(proto.Message): + r"""The request message for the CreateTrigger method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this trigger. + trigger (google.cloud.eventarc_v1.types.Trigger): + Required. The trigger to create. + trigger_id (str): + Required. The user-provided ID to be assigned + to the trigger. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + trigger: gce_trigger.Trigger = proto.Field( + proto.MESSAGE, + number=2, + message=gce_trigger.Trigger, + ) + trigger_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateTriggerRequest(proto.Message): + r"""The request message for the UpdateTrigger method. + + Attributes: + trigger (google.cloud.eventarc_v1.types.Trigger): + The trigger to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to be updated; only fields explicitly provided + are updated. If no field mask is provided, all provided + fields in the request are updated. To update all fields, + provide a field mask of "*". + allow_missing (bool): + If set to true, and the trigger is not found, a new trigger + will be created. In this situation, ``update_mask`` is + ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + trigger: gce_trigger.Trigger = proto.Field( + proto.MESSAGE, + number=1, + message=gce_trigger.Trigger, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteTriggerRequest(proto.Message): + r"""The request message for the DeleteTrigger method. + + Attributes: + name (str): + Required. The name of the trigger to be + deleted. + etag (str): + If provided, the trigger will only be deleted + if the etag matches the current etag on the + resource. + allow_missing (bool): + If set to true, and the trigger is not found, + the request will succeed but no action will be + taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetChannelRequest(proto.Message): + r"""The request message for the GetChannel method. + + Attributes: + name (str): + Required. The name of the channel to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListChannelsRequest(proto.Message): + r"""The request message for the ListChannels method. + + Attributes: + parent (str): + Required. The parent collection to list + channels on. + page_size (int): + The maximum number of channels to return on + each page. + Note: The service may send fewer. + page_token (str): + The page token; provide the value from the + ``next_page_token`` field in a previous ``ListChannels`` + call to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListChannels`` must match the call that provided the page + token. + order_by (str): + The sorting order of the resources returned. Value should be + a comma-separated list of fields. The default sorting order + is ascending. To specify descending order for a field, + append a ``desc`` suffix; for example: + ``name desc, channel_id``. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListChannelsResponse(proto.Message): + r"""The response message for the ``ListChannels`` method. + + Attributes: + channels (MutableSequence[google.cloud.eventarc_v1.types.Channel]): + The requested channels, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListChannels`` to request + the next page. If this is empty, then there are no more + pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + channels: MutableSequence[gce_channel.Channel] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_channel.Channel, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateChannelRequest(proto.Message): + r"""The request message for the CreateChannel method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this channel. + channel (google.cloud.eventarc_v1.types.Channel): + Required. The channel to create. + channel_id (str): + Required. The user-provided ID to be assigned + to the channel. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + channel: gce_channel.Channel = proto.Field( + proto.MESSAGE, + number=2, + message=gce_channel.Channel, + ) + channel_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateChannelRequest(proto.Message): + r"""The request message for the UpdateChannel method. + + Attributes: + channel (google.cloud.eventarc_v1.types.Channel): + The channel to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to be updated; only fields explicitly provided + are updated. If no field mask is provided, all provided + fields in the request are updated. To update all fields, + provide a field mask of "*". + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + channel: gce_channel.Channel = proto.Field( + proto.MESSAGE, + number=1, + message=gce_channel.Channel, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteChannelRequest(proto.Message): + r"""The request message for the DeleteChannel method. + + Attributes: + name (str): + Required. The name of the channel to be + deleted. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class GetProviderRequest(proto.Message): + r"""The request message for the GetProvider method. + + Attributes: + name (str): + Required. The name of the provider to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProvidersRequest(proto.Message): + r"""The request message for the ListProviders method. + + Attributes: + parent (str): + Required. The parent of the provider to get. + page_size (int): + The maximum number of providers to return on + each page. + page_token (str): + The page token; provide the value from the + ``next_page_token`` field in a previous ``ListProviders`` + call to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListProviders`` must match the call that provided the page + token. + order_by (str): + The sorting order of the resources returned. Value should be + a comma-separated list of fields. The default sorting oder + is ascending. To specify descending order for a field, + append a ``desc`` suffix; for example: ``name desc, _id``. + filter (str): + The filter field that the list request will + filter on. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListProvidersResponse(proto.Message): + r"""The response message for the ``ListProviders`` method. + + Attributes: + providers (MutableSequence[google.cloud.eventarc_v1.types.Provider]): + The requested providers, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListProviders`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + providers: MutableSequence[discovery.Provider] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=discovery.Provider, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetChannelConnectionRequest(proto.Message): + r"""The request message for the GetChannelConnection method. + + Attributes: + name (str): + Required. The name of the channel connection + to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListChannelConnectionsRequest(proto.Message): + r"""The request message for the ListChannelConnections method. + + Attributes: + parent (str): + Required. The parent collection from which to + list channel connections. + page_size (int): + The maximum number of channel connections to + return on each page. + Note: The service may send fewer responses. + page_token (str): + The page token; provide the value from the + ``next_page_token`` field in a previous + ``ListChannelConnections`` call to retrieve the subsequent + page. + + When paginating, all other parameters provided to + ``ListChannelConnetions`` match the call that provided the + page token. + """ + + 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 ListChannelConnectionsResponse(proto.Message): + r"""The response message for the ``ListChannelConnections`` method. + + Attributes: + channel_connections (MutableSequence[google.cloud.eventarc_v1.types.ChannelConnection]): + The requested channel connections, up to the number + specified in ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListChannelConnections`` + to request the next page. If this is empty, then there are + no more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + channel_connections: MutableSequence[gce_channel_connection.ChannelConnection] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_channel_connection.ChannelConnection, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateChannelConnectionRequest(proto.Message): + r"""The request message for the CreateChannelConnection method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this channel connection. + channel_connection (google.cloud.eventarc_v1.types.ChannelConnection): + Required. Channel connection to create. + channel_connection_id (str): + Required. The user-provided ID to be assigned + to the channel connection. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + channel_connection: gce_channel_connection.ChannelConnection = proto.Field( + proto.MESSAGE, + number=2, + message=gce_channel_connection.ChannelConnection, + ) + channel_connection_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteChannelConnectionRequest(proto.Message): + r"""The request message for the DeleteChannelConnection method. + + Attributes: + name (str): + Required. The name of the channel connection + to delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateGoogleChannelConfigRequest(proto.Message): + r"""The request message for the UpdateGoogleChannelConfig method. + + Attributes: + google_channel_config (google.cloud.eventarc_v1.types.GoogleChannelConfig): + Required. The config to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to be updated; only fields explicitly provided + are updated. If no field mask is provided, all provided + fields in the request are updated. To update all fields, + provide a field mask of "*". + """ + + google_channel_config: gce_google_channel_config.GoogleChannelConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gce_google_channel_config.GoogleChannelConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetGoogleChannelConfigRequest(proto.Message): + r"""The request message for the GetGoogleChannelConfig method. + + Attributes: + name (str): + Required. The name of the config to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetMessageBusRequest(proto.Message): + r"""The request message for the GetMessageBus method. + + Attributes: + name (str): + Required. The name of the message bus to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMessageBusesRequest(proto.Message): + r"""The request message for the ListMessageBuses method. + + Attributes: + parent (str): + Required. The parent collection to list + triggers on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filtersare + described in https://google.aip.dev/160. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListMessageBusesResponse(proto.Message): + r"""The response message for the ``ListMessageBuses`` method. + + Attributes: + message_buses (MutableSequence[google.cloud.eventarc_v1.types.MessageBus]): + The requested message buses, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListMessageBuses`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + message_buses: MutableSequence[gce_message_bus.MessageBus] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_message_bus.MessageBus, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListMessageBusEnrollmentsRequest(proto.Message): + r"""The request message for the ``ListMessageBusEnrollments`` method. + + Attributes: + parent (str): + Required. The parent message bus to list + enrollments on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + """ + + 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 ListMessageBusEnrollmentsResponse(proto.Message): + r"""The response message for the ``ListMessageBusEnrollments`` method.\` + + Attributes: + enrollments (MutableSequence[str]): + The requested enrollments, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to + ``ListMessageBusEnrollments`` to request the next page. If + this is empty, then there are no more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + enrollments: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateMessageBusRequest(proto.Message): + r"""The request message for the CreateMessageBus method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this message bus. + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The message bus to create. + message_bus_id (str): + Required. The user-provided ID to be assigned to the + MessageBus. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + message_bus: gce_message_bus.MessageBus = proto.Field( + proto.MESSAGE, + number=2, + message=gce_message_bus.MessageBus, + ) + message_bus_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateMessageBusRequest(proto.Message): + r"""The request message for the UpdateMessageBus method. + + Attributes: + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The MessageBus to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the MessageBus is not found, a + new MessageBus will be created. In this situation, + ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + message_bus: gce_message_bus.MessageBus = proto.Field( + proto.MESSAGE, + number=1, + message=gce_message_bus.MessageBus, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteMessageBusRequest(proto.Message): + r"""The request message for the DeleteMessageBus method. + + Attributes: + name (str): + Required. The name of the MessageBus to be + deleted. + etag (str): + Optional. If provided, the MessageBus will + only be deleted if the etag matches the current + etag on the resource. + allow_missing (bool): + Optional. If set to true, and the MessageBus + is not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetEnrollmentRequest(proto.Message): + r"""The request message for the GetEnrollment method. + + Attributes: + name (str): + Required. The name of the Enrollment to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEnrollmentsRequest(proto.Message): + r"""The request message for the ListEnrollments method. + + Attributes: + parent (str): + Required. The parent collection to list + triggers on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filtersare + described in https://google.aip.dev/160. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEnrollmentsResponse(proto.Message): + r"""The response message for the ``ListEnrollments`` method. + + Attributes: + enrollments (MutableSequence[google.cloud.eventarc_v1.types.Enrollment]): + The requested Enrollments, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListEnrollments`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + enrollments: MutableSequence[gce_enrollment.Enrollment] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_enrollment.Enrollment, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateEnrollmentRequest(proto.Message): + r"""The request message for the CreateEnrollment method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this enrollment. + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The enrollment to create. + enrollment_id (str): + Required. The user-provided ID to be assigned to the + Enrollment. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + enrollment: gce_enrollment.Enrollment = proto.Field( + proto.MESSAGE, + number=2, + message=gce_enrollment.Enrollment, + ) + enrollment_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateEnrollmentRequest(proto.Message): + r"""The request message for the UpdateEnrollment method. + + Attributes: + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The Enrollment to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the Enrollment is not found, a + new Enrollment will be created. In this situation, + ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + enrollment: gce_enrollment.Enrollment = proto.Field( + proto.MESSAGE, + number=1, + message=gce_enrollment.Enrollment, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteEnrollmentRequest(proto.Message): + r"""The request message for the DeleteEnrollment method. + + Attributes: + name (str): + Required. The name of the Enrollment to be + deleted. + etag (str): + Optional. If provided, the Enrollment will + only be deleted if the etag matches the current + etag on the resource. + allow_missing (bool): + Optional. If set to true, and the Enrollment + is not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetPipelineRequest(proto.Message): + r"""The request message for the GetPipeline method. + + Attributes: + name (str): + Required. The name of the pipeline to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPipelinesRequest(proto.Message): + r"""The request message for the ListPipelines method. + + Attributes: + parent (str): + Required. The parent collection to list + pipelines on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filters are + described in https://google.aip.dev/160. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListPipelinesResponse(proto.Message): + r"""The response message for the ListPipelines method. + + Attributes: + pipelines (MutableSequence[google.cloud.eventarc_v1.types.Pipeline]): + The requested pipelines, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListPipelines`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + pipelines: MutableSequence[gce_pipeline.Pipeline] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_pipeline.Pipeline, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreatePipelineRequest(proto.Message): + r"""The request message for the CreatePipeline method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this pipeline. + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The pipeline to create. + pipeline_id (str): + Required. The user-provided ID to be assigned + to the Pipeline. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + pipeline: gce_pipeline.Pipeline = proto.Field( + proto.MESSAGE, + number=2, + message=gce_pipeline.Pipeline, + ) + pipeline_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdatePipelineRequest(proto.Message): + r"""The request message for the UpdatePipeline method. + + Attributes: + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The Pipeline to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the Pipeline is not found, a + new Pipeline will be created. In this situation, + ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + pipeline: gce_pipeline.Pipeline = proto.Field( + proto.MESSAGE, + number=1, + message=gce_pipeline.Pipeline, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeletePipelineRequest(proto.Message): + r"""The request message for the DeletePipeline method. + + Attributes: + name (str): + Required. The name of the Pipeline to be + deleted. + etag (str): + Optional. If provided, the Pipeline will only + be deleted if the etag matches the current etag + on the resource. + allow_missing (bool): + Optional. If set to true, and the Pipeline is + not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetGoogleApiSourceRequest(proto.Message): + r"""The request message for the GetGoogleApiSource method. + + Attributes: + name (str): + Required. The name of the google api source + to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListGoogleApiSourcesRequest(proto.Message): + r"""The request message for the ListGoogleApiSources method. + + Attributes: + parent (str): + Required. The parent collection to list + GoogleApiSources on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filtersare + described in https://google.aip.dev/160. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListGoogleApiSourcesResponse(proto.Message): + r"""The response message for the ``ListGoogleApiSources`` method. + + Attributes: + google_api_sources (MutableSequence[google.cloud.eventarc_v1.types.GoogleApiSource]): + The requested GoogleApiSources, up to the number specified + in ``page_size``. + next_page_token (str): + A page token that can be sent to + ``ListMessageBusEnrollments`` to request the next page. If + this is empty, then there are no more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + google_api_sources: MutableSequence[gce_google_api_source.GoogleApiSource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_google_api_source.GoogleApiSource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateGoogleApiSourceRequest(proto.Message): + r"""The request message for the CreateGoogleApiSource method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this google api source. + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The google api source to create. + google_api_source_id (str): + Required. The user-provided ID to be assigned to the + GoogleApiSource. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + google_api_source: gce_google_api_source.GoogleApiSource = proto.Field( + proto.MESSAGE, + number=2, + message=gce_google_api_source.GoogleApiSource, + ) + google_api_source_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateGoogleApiSourceRequest(proto.Message): + r"""The request message for the UpdateGoogleApiSource method. + + Attributes: + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The GoogleApiSource to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the GoogleApiSource is not + found, a new GoogleApiSource will be created. In this + situation, ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + google_api_source: gce_google_api_source.GoogleApiSource = proto.Field( + proto.MESSAGE, + number=1, + message=gce_google_api_source.GoogleApiSource, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteGoogleApiSourceRequest(proto.Message): + r"""The request message for the DeleteGoogleApiSource method. + + Attributes: + name (str): + Required. The name of the GoogleApiSource to + be deleted. + etag (str): + Optional. If provided, the MessageBus will + only be deleted if the etag matches the current + etag on the resource. + allow_missing (bool): + Optional. If set to true, and the MessageBus + is not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py new file mode 100644 index 000000000000..daf49f4929b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.eventarc_v1.types import logging_config as gce_logging_config +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'GoogleApiSource', + }, +) + + +class GoogleApiSource(proto.Message): + r"""A GoogleApiSource represents a subscription of 1P events from + a MessageBus. + + Attributes: + name (str): + Identifier. Resource name of the form + projects/{project}/locations/{location}/googleApiSources/{google_api_source} + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on update and delete requests + to ensure that the client has an up-to-date + value before proceeding. + 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. + labels (MutableMapping[str, str]): + Optional. Resource labels. + annotations (MutableMapping[str, str]): + Optional. Resource annotations. + display_name (str): + Optional. Resource display name. + destination (str): + Required. Destination is the message bus that the + GoogleApiSource is delivering to. It must be point to the + full resource name of a MessageBus. Format: + "projects/{PROJECT_ID}/locations/{region}/messagesBuses/{MESSAGE_BUS_ID) + crypto_key_name (str): + Optional. Resource name of a KMS crypto key (managed by the + user) used to encrypt/decrypt their event data. + + It must match the pattern + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + logging_config (google.cloud.eventarc_v1.types.LoggingConfig): + Optional. Config to control Platform logging + for the GoogleApiSource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + destination: str = proto.Field( + proto.STRING, + number=9, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=10, + ) + logging_config: gce_logging_config.LoggingConfig = proto.Field( + proto.MESSAGE, + number=11, + message=gce_logging_config.LoggingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py new file mode 100644 index 000000000000..c99e4bc09554 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'GoogleChannelConfig', + }, +) + + +class GoogleChannelConfig(proto.Message): + r"""A GoogleChannelConfig is a resource that stores the custom + settings respected by Eventarc first-party triggers in the + matching region. Once configured, first-party event data will be + protected using the specified custom managed encryption key + instead of Google-managed encryption keys. + + Attributes: + name (str): + Required. The resource name of the config. Must be in the + format of, + ``projects/{project}/locations/{location}/googleChannelConfig``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + crypto_key_name (str): + Optional. Resource name of a KMS crypto key (managed by the + user) used to encrypt/decrypt their event data. + + It must match the pattern + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py new file mode 100644 index 000000000000..31f742eb9a89 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.eventarc.v1', + manifest={ + 'LoggingConfig', + }, +) + + +class LoggingConfig(proto.Message): + r"""The configuration for Platform Telemetry logging for Eventarc + Advanced resources. + + Attributes: + log_severity (google.cloud.eventarc_v1.types.LoggingConfig.LogSeverity): + Optional. The minimum severity of logs that + will be sent to Stackdriver/Platform Telemetry. + Logs at severitiy ≥ this value will be sent, + unless it is NONE. + """ + class LogSeverity(proto.Enum): + r"""The different severities for logging supported by Eventarc + Advanced resources. + This enum is an exhaustive list of log severities and is FROZEN. + Do not expect new values to be added. + + Values: + LOG_SEVERITY_UNSPECIFIED (0): + Log severity is not specified. This value is treated the + same as NONE, but is used to distinguish between no update + and update to NONE in update_masks. + NONE (1): + Default value at resource creation, presence + of this value must be treated as no + logging/disable logging. + DEBUG (2): + Debug or trace level logging. + INFO (3): + Routine information, such as ongoing status + or performance. + NOTICE (4): + Normal but significant events, such as start + up, shut down, or a configuration change. + WARNING (5): + Warning events might cause problems. + ERROR (6): + Error events are likely to cause problems. + CRITICAL (7): + Critical events cause more severe problems or + outages. + ALERT (8): + A person must take action immediately. + EMERGENCY (9): + One or more systems are unusable. + """ + LOG_SEVERITY_UNSPECIFIED = 0 + NONE = 1 + DEBUG = 2 + INFO = 3 + NOTICE = 4 + WARNING = 5 + ERROR = 6 + CRITICAL = 7 + ALERT = 8 + EMERGENCY = 9 + + log_severity: LogSeverity = proto.Field( + proto.ENUM, + number=1, + enum=LogSeverity, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py new file mode 100644 index 000000000000..826c24bd5950 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.eventarc_v1.types import logging_config as gce_logging_config +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'MessageBus', + }, +) + + +class MessageBus(proto.Message): + r"""MessageBus for the messages flowing through the system. The + admin has visibility and control over the messages being + published and consumed and can restrict publishers and + subscribers to only a subset of data available in the system by + defining authorization policies. + + Attributes: + name (str): + Identifier. Resource name of the form + projects/{project}/locations/{location}/messageBuses/{message_bus} + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on update and delete requests + to ensure that the client has an up-to-date + value before proceeding. + 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. + labels (MutableMapping[str, str]): + Optional. Resource labels. + annotations (MutableMapping[str, str]): + Optional. Resource annotations. + display_name (str): + Optional. Resource display name. + crypto_key_name (str): + Optional. Resource name of a KMS crypto key (managed by the + user) used to encrypt/decrypt their event data. + + It must match the pattern + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + logging_config (google.cloud.eventarc_v1.types.LoggingConfig): + Optional. Config to control Platform logging + for the Message Bus. This log configuration is + applied to the Message Bus itself, and all the + Enrollments attached to it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + 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, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=10, + ) + logging_config: gce_logging_config.LoggingConfig = proto.Field( + proto.MESSAGE, + number=11, + message=gce_logging_config.LoggingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py new file mode 100644 index 000000000000..46d0cc094778 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.eventarc.v1', + manifest={ + 'NetworkConfig', + }, +) + + +class NetworkConfig(proto.Message): + r"""Network Configuration that can be inherited by other protos. + + Attributes: + network_attachment (str): + Required. Name of the NetworkAttachment that allows access + to the customer's VPC. Format: + ``projects/{PROJECT_ID}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}`` + """ + + network_attachment: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py new file mode 100644 index 000000000000..d0c483f718ad --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py @@ -0,0 +1,838 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.eventarc_v1.types import logging_config as gce_logging_config +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'Pipeline', + }, +) + + +class Pipeline(proto.Message): + r"""A representation of the Pipeline resource. + + Attributes: + name (str): + Identifier. The resource name of the Pipeline. Must be + unique within the location of the project and must be in + ``projects/{project}/locations/{location}/pipelines/{pipeline}`` + format. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + A timestamp in RFC3339 UTC "Zulu" format, with + nanosecond resolution and up to nine fractional + digits. Examples: "2014-10-02T15:01:23Z" and + "2014-10-02T15:01:23.045123456Z". + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + A timestamp in RFC3339 UTC "Zulu" format, with + nanosecond resolution and up to nine fractional + digits. Examples: "2014-10-02T15:01:23Z" and + "2014-10-02T15:01:23.045123456Z". + labels (MutableMapping[str, str]): + Optional. User labels attached to the + Pipeline that can be used to group resources. An + object containing a list of "key": value pairs. + Example: { "name": "wrench", "mass": "1.3kg", + "count": "3" }. + uid (str): + Output only. Server-assigned unique + identifier for the Pipeline. The value is a + UUID4 string and guaranteed to remain unchanged + until the resource is deleted. + annotations (MutableMapping[str, str]): + Optional. User-defined annotations. See + https://google.aip.dev/128#annotations. + display_name (str): + Optional. Display name of resource. + destinations (MutableSequence[google.cloud.eventarc_v1.types.Pipeline.Destination]): + Required. List of destinations to which + messages will be forwarded. Currently, exactly + one destination is supported per Pipeline. + mediations (MutableSequence[google.cloud.eventarc_v1.types.Pipeline.Mediation]): + Optional. List of mediation operations to be + performed on the message. Currently, only one + Transformation operation is allowed in each + Pipeline. + crypto_key_name (str): + Optional. Resource name of a KMS crypto key + (managed by the user) used to encrypt/decrypt + the event data. If not set, an internal + Google-owned key will be used to encrypt + messages. It must match the pattern + "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}". + input_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): + Optional. The payload format expected for the messages + received by the Pipeline. If input_payload_format is set + then any messages not matching this format will be treated + as persistent errors. If input_payload_format is not set, + then the message data will be treated as an opaque binary + and no output format can be set on the Pipeline through the + Pipeline.Destination.output_payload_format field. Any + Mediations on the Pipeline that involve access to the data + field will fail as persistent errors. + logging_config (google.cloud.eventarc_v1.types.LoggingConfig): + Optional. Config to control Platform Logging + for Pipelines. + retry_policy (google.cloud.eventarc_v1.types.Pipeline.RetryPolicy): + Optional. The retry policy to use in the + pipeline. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on create requests to ensure + that the client has an up-to-date value before + proceeding. + """ + + class MessagePayloadFormat(proto.Message): + r"""Represents the format of message data. + + 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: + protobuf (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.ProtobufFormat): + Optional. Protobuf format. + + This field is a member of `oneof`_ ``kind``. + avro (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.AvroFormat): + Optional. Avro format. + + This field is a member of `oneof`_ ``kind``. + json (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.JsonFormat): + Optional. JSON format. + + This field is a member of `oneof`_ ``kind``. + """ + + class JsonFormat(proto.Message): + r"""The format of a JSON message payload. + """ + + class ProtobufFormat(proto.Message): + r"""The format of a Protobuf message payload. + + Attributes: + schema_definition (str): + Optional. The entire schema definition is + stored in this field. + """ + + schema_definition: str = proto.Field( + proto.STRING, + number=1, + ) + + class AvroFormat(proto.Message): + r"""The format of an AVRO message payload. + + Attributes: + schema_definition (str): + Optional. The entire schema definition is + stored in this field. + """ + + schema_definition: str = proto.Field( + proto.STRING, + number=1, + ) + + protobuf: 'Pipeline.MessagePayloadFormat.ProtobufFormat' = proto.Field( + proto.MESSAGE, + number=1, + oneof='kind', + message='Pipeline.MessagePayloadFormat.ProtobufFormat', + ) + avro: 'Pipeline.MessagePayloadFormat.AvroFormat' = proto.Field( + proto.MESSAGE, + number=2, + oneof='kind', + message='Pipeline.MessagePayloadFormat.AvroFormat', + ) + json: 'Pipeline.MessagePayloadFormat.JsonFormat' = proto.Field( + proto.MESSAGE, + number=3, + oneof='kind', + message='Pipeline.MessagePayloadFormat.JsonFormat', + ) + + class Destination(proto.Message): + r"""Represents a target of an invocation over HTTP. + + 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: + network_config (google.cloud.eventarc_v1.types.Pipeline.Destination.NetworkConfig): + Optional. Network config is used to configure + how Pipeline resolves and connects to a + destination. + http_endpoint (google.cloud.eventarc_v1.types.Pipeline.Destination.HttpEndpoint): + Optional. An HTTP endpoint destination described by an URI. + If a DNS FQDN is provided as the endpoint, Pipeline will + create a peering zone to the consumer VPC and forward DNS + requests to the VPC specified by network config to resolve + the service endpoint. See: + https://cloud.google.com/dns/docs/zones/zones-overview#peering_zones + + This field is a member of `oneof`_ ``destination_descriptor``. + workflow (str): + Optional. The resource name of the Workflow whose Executions + are triggered by the events. The Workflow resource should be + deployed in the same project as the Pipeline. Format: + ``projects/{project}/locations/{location}/workflows/{workflow}`` + + This field is a member of `oneof`_ ``destination_descriptor``. + message_bus (str): + Optional. The resource name of the Message Bus to which + events should be published. The Message Bus resource should + exist in the same project as the Pipeline. Format: + ``projects/{project}/locations/{location}/messageBuses/{message_bus}`` + + This field is a member of `oneof`_ ``destination_descriptor``. + topic (str): + Optional. The resource name of the Pub/Sub topic to which + events should be published. Format: + ``projects/{project}/locations/{location}/topics/{topic}`` + + This field is a member of `oneof`_ ``destination_descriptor``. + authentication_config (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig): + Optional. An authentication config used to + authenticate message requests, such that + destinations can verify the source. For example, + this can be used with private GCP destinations + that require GCP credentials to access like + Cloud Run. This field is optional and should be + set only by users interested in authenticated + push + output_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): + Optional. The message format before it is delivered to the + destination. If not set, the message will be delivered in + the format it was originally delivered to the Pipeline. This + field can only be set if Pipeline.input_payload_format is + also set. + """ + + class NetworkConfig(proto.Message): + r"""Represents a network config to be used for destination + resolution and connectivity. + + Attributes: + network_attachment (str): + Required. Name of the NetworkAttachment that allows access + to the consumer VPC. Format: + ``projects/{PROJECT_ID}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}`` + """ + + network_attachment: str = proto.Field( + proto.STRING, + number=1, + ) + + class HttpEndpoint(proto.Message): + r"""Represents a HTTP endpoint destination. + + Attributes: + uri (str): + Required. The URI of the HTTP enpdoint. + + The value must be a RFC2396 URI string. Examples: + ``https://svc.us-central1.p.local:8080/route``. Only the + HTTPS protocol is supported. + message_binding_template (str): + Optional. The CEL expression used to modify how the + destination-bound HTTP request is constructed. + + If a binding expression is not specified here, the message + is treated as a CloudEvent and is mapped to the HTTP request + according to the CloudEvent HTTP Protocol Binding Binary + Content Mode. In this representation, all fields except the + ``data`` and ``datacontenttype`` field on the message are + mapped to HTTP request headers with a prefix of ``ce-``. + + To construct the HTTP request payload and the value of the + content-type HTTP header, the payload format is defined as + follows: + + 1) Use the output_payload_format_type on the + Pipeline.Destination if it is set, else: + 2) Use the input_payload_format_type on the Pipeline if it + is set, else: + 3) Treat the payload as opaque binary data. + + The ``data`` field of the message is converted to the + payload format or left as-is for case 3) and then attached + as the payload of the HTTP request. The ``content-type`` + header on the HTTP request is set to the payload format type + or left empty for case 3). However, if a mediation has + updated the ``datacontenttype`` field on the message so that + it is not the same as the payload format type but it is + still a prefix of the payload format type, then the + ``content-type`` header on the HTTP request is set to this + ``datacontenttype`` value. For example, if the + ``datacontenttype`` is "application/json" and the payload + format type is "application/json; charset=utf-8", then the + ``content-type`` header on the HTTP request is set to + "application/json; charset=utf-8". + + If a non-empty binding expression is specified then this + expression is used to modify the default CloudEvent HTTP + Protocol Binding Binary Content representation. The result + of the CEL expression must be a map of key/value pairs which + is used as follows: + + - If a map named ``headers`` exists on the result of the + expression, then its key/value pairs are directly mapped + to the HTTP request headers. The headers values are + constructed from the corresponding value type’s canonical + representation. If the ``headers`` field doesn’t exist + then the resulting HTTP request will be the headers of + the CloudEvent HTTP Binding Binary Content Mode + representation of the final message. Note: If the + specified binding expression, has updated the + ``datacontenttype`` field on the message so that it is + not the same as the payload format type but it is still a + prefix of the payload format type, then the + ``content-type`` header in the ``headers`` map is set to + this ``datacontenttype`` value. + - If a field named ``body`` exists on the result of the + expression then its value is directly mapped to the body + of the request. If the value of the ``body`` field is of + type bytes or string then it is used for the HTTP request + body as-is, with no conversion. If the body field is of + any other type then it is converted to a JSON string. If + the body field does not exist then the resulting payload + of the HTTP request will be data value of the CloudEvent + HTTP Binding Binary Content Mode representation of the + final message as described earlier. + - Any other fields in the resulting expression will be + ignored. + + The CEL expression may access the incoming CloudEvent + message in its definition, as follows: + + - The ``data`` field of the incoming CloudEvent message can + be accessed using the ``message.data`` value. Subfields + of ``message.data`` may also be accessed if an + input_payload_format has been specified on the Pipeline. + - Each attribute of the incoming CloudEvent message can be + accessed using the ``message.`` value, where is + replaced with the name of the attribute. + - Existing headers can be accessed in the CEL expression + using the ``headers`` variable. The ``headers`` variable + defines a map of key/value pairs corresponding to the + HTTP headers of the CloudEvent HTTP Binding Binary + Content Mode representation of the final message as + described earlier. For example, the following CEL + expression can be used to construct an HTTP request by + adding an additional header to the HTTP headers of the + CloudEvent HTTP Binding Binary Content Mode + representation of the final message and by overwriting + the body of the request: + + :: + + { + "headers": headers.merge({"new-header-key": "new-header-value"}), + "body": "new-body" + } + + Additionally, the following CEL extension functions are + provided for use in this CEL expression: + + - toBase64Url: map.toBase64Url() -> string + + - Converts a CelValue to a base64url encoded string + + - toJsonString: map.toJsonString() -> string + + - Converts a CelValue to a JSON string + + - merge: map1.merge(map2) -> map3 + + - Merges the passed CEL map with the existing CEL map + the function is applied to. + - If the same key exists in both maps, if the key's + value is type map both maps are merged else the value + from the passed map is used. + + - denormalize: map.denormalize() -> map + + - Denormalizes a CEL map such that every value of type + map or key in the map is expanded to return a single + level map. + - The resulting keys are "." separated indices of the + map keys. + - For example: { "a": 1, "b": { "c": 2, "d": 3 } "e": + [4, 5] } .denormalize() -> { "a": 1, "b.c": 2, "b.d": + 3, "e.0": 4, "e.1": 5 } + + - setField: map.setField(key, value) -> message + + - Sets the field of the message with the given key to + the given value. + - If the field is not present it will be added. + - If the field is present it will be overwritten. + - The key can be a dot separated path to set a field in + a nested message. + - Key must be of type string. + - Value may be any valid type. + + - removeFields: map.removeFields([key1, key2, ...]) -> + message + + - Removes the fields of the map with the given keys. + - The keys can be a dot separated path to remove a field + in a nested message. + - If a key is not found it will be ignored. + - Keys must be of type string. + + - toMap: [map1, map2, ...].toMap() -> map + + - Converts a CEL list of CEL maps to a single CEL map + + - toDestinationPayloadFormat(): + message.data.toDestinationPayloadFormat() -> string or + bytes + + - Converts the message data to the destination payload + format specified in + Pipeline.Destination.output_payload_format + - This function is meant to be applied to the + message.data field. + - If the destination payload format is not set, the + function will return the message data unchanged. + + - toCloudEventJsonWithPayloadFormat: + message.toCloudEventJsonWithPayloadFormat() -> map + + - Converts a message to the corresponding structure of + JSON format for CloudEvents + - This function applies toDestinationPayloadFormat() to + the message data. It also sets the corresponding + datacontenttype of the CloudEvent, as indicated by + Pipeline.Destination.output_payload_format. If no + output_payload_format is set it will use the existing + datacontenttype on the CloudEvent if present, else + leave datacontenttype absent. + - This function expects that the content of the message + will adhere to the standard CloudEvent format. If it + doesn’t then this function will fail. + - The result is a CEL map that corresponds to the JSON + representation of the CloudEvent. To convert that data + to a JSON string it can be chained with the + toJsonString function. + + The Pipeline expects that the message it receives adheres to + the standard CloudEvent format. If it doesn’t then the + outgoing message request may fail with a persistent error. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + message_binding_template: str = proto.Field( + proto.STRING, + number=3, + ) + + class AuthenticationConfig(proto.Message): + r"""Represents a config used to authenticate message requests. + + 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: + google_oidc (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OidcToken): + Optional. This authenticate method will apply + Google OIDC tokens signed by a GCP service + account to the requests. + + This field is a member of `oneof`_ ``authentication_method_descriptor``. + oauth_token (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OAuthToken): + Optional. If specified, an `OAuth + token `__ + will be generated and attached as an ``Authorization`` + header in the HTTP request. + + This type of authorization should generally only be used + when calling Google APIs hosted on \*.googleapis.com. + + This field is a member of `oneof`_ ``authentication_method_descriptor``. + """ + + class OidcToken(proto.Message): + r"""Represents a config used to authenticate with a Google OIDC + token using a GCP service account. Use this authentication + method to invoke your Cloud Run and Cloud Functions destinations + or HTTP endpoints that support Google OIDC. + + Attributes: + service_account (str): + Required. Service account email used to generate the OIDC + Token. The principal who calls this API must have + iam.serviceAccounts.actAs permission in the service account. + See + https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common + for more information. Eventarc service agents must have + roles/roles/iam.serviceAccountTokenCreator role to allow the + Pipeline to create OpenID tokens for authenticated requests. + audience (str): + Optional. Audience to be used to generate the + OIDC Token. The audience claim identifies the + recipient that the JWT is intended for. If + unspecified, the destination URI will be used. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + audience: str = proto.Field( + proto.STRING, + number=2, + ) + + class OAuthToken(proto.Message): + r"""Contains information needed for generating an `OAuth + token `__. + This type of authorization should generally only be used when + calling Google APIs hosted on \*.googleapis.com. + + Attributes: + service_account (str): + Required. Service account email used to generate the `OAuth + token `__. + The principal who calls this API must have + iam.serviceAccounts.actAs permission in the service account. + See + https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common + for more information. Eventarc service agents must have + roles/roles/iam.serviceAccountTokenCreator role to allow + Pipeline to create OAuth2 tokens for authenticated requests. + scope (str): + Optional. OAuth scope to be used for + generating OAuth access token. If not specified, + "https://www.googleapis.com/auth/cloud-platform" + will be used. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + scope: str = proto.Field( + proto.STRING, + number=2, + ) + + google_oidc: 'Pipeline.Destination.AuthenticationConfig.OidcToken' = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication_method_descriptor', + message='Pipeline.Destination.AuthenticationConfig.OidcToken', + ) + oauth_token: 'Pipeline.Destination.AuthenticationConfig.OAuthToken' = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication_method_descriptor', + message='Pipeline.Destination.AuthenticationConfig.OAuthToken', + ) + + network_config: 'Pipeline.Destination.NetworkConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='Pipeline.Destination.NetworkConfig', + ) + http_endpoint: 'Pipeline.Destination.HttpEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='destination_descriptor', + message='Pipeline.Destination.HttpEndpoint', + ) + workflow: str = proto.Field( + proto.STRING, + number=3, + oneof='destination_descriptor', + ) + message_bus: str = proto.Field( + proto.STRING, + number=4, + oneof='destination_descriptor', + ) + topic: str = proto.Field( + proto.STRING, + number=8, + oneof='destination_descriptor', + ) + authentication_config: 'Pipeline.Destination.AuthenticationConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='Pipeline.Destination.AuthenticationConfig', + ) + output_payload_format: 'Pipeline.MessagePayloadFormat' = proto.Field( + proto.MESSAGE, + number=6, + message='Pipeline.MessagePayloadFormat', + ) + + class Mediation(proto.Message): + r"""Mediation defines different ways to modify the Pipeline. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + transformation (google.cloud.eventarc_v1.types.Pipeline.Mediation.Transformation): + Optional. How the Pipeline is to transform + messages + + This field is a member of `oneof`_ ``mediation_descriptor``. + """ + + class Transformation(proto.Message): + r"""Transformation defines the way to transform an incoming + message. + + Attributes: + transformation_template (str): + Optional. The CEL expression template to apply to transform + messages. The following CEL extension functions are provided + for use in this CEL expression: + + - merge: map1.merge(map2) -> map3 + + - Merges the passed CEL map with the existing CEL map + the function is applied to. + - If the same key exists in both maps, if the key's + value is type map both maps are merged else the value + from the passed map is used. + + - denormalize: map.denormalize() -> map + + - Denormalizes a CEL map such that every value of type + map or key in the map is expanded to return a single + level map. + - The resulting keys are "." separated indices of the + map keys. + - For example: { "a": 1, "b": { "c": 2, "d": 3 } "e": + [4, 5] } .denormalize() -> { "a": 1, "b.c": 2, "b.d": + 3, "e.0": 4, "e.1": 5 } + + - setField: map.setField(key, value) -> message + + - Sets the field of the message with the given key to + the given value. + - If the field is not present it will be added. + - If the field is present it will be overwritten. + - The key can be a dot separated path to set a field in + a nested message. + - Key must be of type string. + - Value may be any valid type. + + - removeFields: map.removeFields([key1, key2, ...]) -> + message + + - Removes the fields of the map with the given keys. + - The keys can be a dot separated path to remove a field + in a nested message. + - If a key is not found it will be ignored. + - Keys must be of type string. + + - toMap: [map1, map2, ...].toMap() -> map + + - Converts a CEL list of CEL maps to a single CEL map + + - toDestinationPayloadFormat(): + message.data.toDestinationPayloadFormat() -> string or + bytes + + - Converts the message data to the destination payload + format specified in + Pipeline.Destination.output_payload_format + - This function is meant to be applied to the + message.data field. + - If the destination payload format is not set, the + function will return the message data unchanged. + + - toCloudEventJsonWithPayloadFormat: + message.toCloudEventJsonWithPayloadFormat() -> map + + - Converts a message to the corresponding structure of + JSON format for CloudEvents + - This function applies toDestinationPayloadFormat() to + the message data. It also sets the corresponding + datacontenttype of the CloudEvent, as indicated by + Pipeline.Destination.output_payload_format. If no + output_payload_format is set it will use the existing + datacontenttype on the CloudEvent if present, else + leave datacontenttype absent. + - This function expects that the content of the message + will adhere to the standard CloudEvent format. If it + doesn’t then this function will fail. + - The result is a CEL map that corresponds to the JSON + representation of the CloudEvent. To convert that data + to a JSON string it can be chained with the + toJsonString function. + """ + + transformation_template: str = proto.Field( + proto.STRING, + number=1, + ) + + transformation: 'Pipeline.Mediation.Transformation' = proto.Field( + proto.MESSAGE, + number=1, + oneof='mediation_descriptor', + message='Pipeline.Mediation.Transformation', + ) + + class RetryPolicy(proto.Message): + r"""The retry policy configuration for the Pipeline. The pipeline + exponentially backs off in case the destination is non responsive or + returns a retryable error code. The default semantics are as + follows: The backoff starts with a 5 second delay and doubles the + delay after each failed attempt (10 seconds, 20 seconds, 40 seconds, + etc.). The delay is capped at 60 seconds by default. Please note + that if you set the min_retry_delay and max_retry_delay fields to + the same value this will make the duration between retries constant. + + Attributes: + max_attempts (int): + Optional. The maximum number of delivery + attempts for any message. The value must be + between 1 and 100. The default value for this + field is 5. + min_retry_delay (google.protobuf.duration_pb2.Duration): + Optional. The minimum amount of seconds to + wait between retry attempts. The value must be + between 1 and 600. The default value for this + field is 5. + max_retry_delay (google.protobuf.duration_pb2.Duration): + Optional. The maximum amount of seconds to + wait between retry attempts. The value must be + between 1 and 600. The default value for this + field is 60. + """ + + max_attempts: int = proto.Field( + proto.INT32, + number=1, + ) + min_retry_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + max_retry_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + uid: str = proto.Field( + proto.STRING, + number=5, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + display_name: str = proto.Field( + proto.STRING, + number=7, + ) + destinations: MutableSequence[Destination] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=Destination, + ) + mediations: MutableSequence[Mediation] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=Mediation, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=10, + ) + input_payload_format: MessagePayloadFormat = proto.Field( + proto.MESSAGE, + number=11, + message=MessagePayloadFormat, + ) + logging_config: gce_logging_config.LoggingConfig = proto.Field( + proto.MESSAGE, + number=12, + message=gce_logging_config.LoggingConfig, + ) + retry_policy: RetryPolicy = proto.Field( + proto.MESSAGE, + number=13, + message=RetryPolicy, + ) + etag: str = proto.Field( + proto.STRING, + number=99, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py new file mode 100644 index 000000000000..68e45d11944f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py @@ -0,0 +1,489 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.eventarc_v1.types import network_config as gce_network_config +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.eventarc.v1', + manifest={ + 'Trigger', + 'EventFilter', + 'StateCondition', + 'Destination', + 'Transport', + 'CloudRun', + 'GKE', + 'Pubsub', + 'HttpEndpoint', + }, +) + + +class Trigger(proto.Message): + r"""A representation of the trigger resource. + + Attributes: + name (str): + Required. The resource name of the trigger. Must be unique + within the location of the project and must be in + ``projects/{project}/locations/{location}/triggers/{trigger}`` + format. + 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. + 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. + event_filters (MutableSequence[google.cloud.eventarc_v1.types.EventFilter]): + Required. Unordered list. The list of filters + that applies to event attributes. Only events + that match all the provided filters are sent to + the destination. + service_account (str): + Optional. The IAM service account email associated with the + trigger. The service account represents the identity of the + trigger. + + The ``iam.serviceAccounts.actAs`` permission must be granted + on the service account to allow a principal to impersonate + the service account. For more information, see the `Roles + and permissions `__ + page specific to the trigger destination. + destination (google.cloud.eventarc_v1.types.Destination): + Required. Destination specifies where the + events should be sent to. + transport (google.cloud.eventarc_v1.types.Transport): + Optional. To deliver messages, Eventarc might + use other Google Cloud products as a transport + intermediary. This field contains a reference to + that transport intermediary. This information + can be used for debugging purposes. + labels (MutableMapping[str, str]): + Optional. User labels attached to the + triggers that can be used to group resources. + channel (str): + Optional. The name of the channel associated with the + trigger in + ``projects/{project}/locations/{location}/channels/{channel}`` + format. You must provide a channel to receive events from + Eventarc SaaS partners. + conditions (MutableMapping[str, google.cloud.eventarc_v1.types.StateCondition]): + Output only. The reason(s) why a trigger is + in FAILED state. + event_data_content_type (str): + Optional. EventDataContentType specifies the type of payload + in MIME format that is expected from the CloudEvent data + field. This is set to ``application/json`` if the value is + not defined. + satisfies_pzs (bool): + Output only. Whether or not this Trigger + satisfies the requirements of physical zone + separation + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on create requests to ensure + that the client has an up-to-date value before + proceeding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + event_filters: MutableSequence['EventFilter'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='EventFilter', + ) + service_account: str = proto.Field( + proto.STRING, + number=9, + ) + destination: 'Destination' = proto.Field( + proto.MESSAGE, + number=10, + message='Destination', + ) + transport: 'Transport' = proto.Field( + proto.MESSAGE, + number=11, + message='Transport', + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + channel: str = proto.Field( + proto.STRING, + number=13, + ) + conditions: MutableMapping[str, 'StateCondition'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=15, + message='StateCondition', + ) + event_data_content_type: str = proto.Field( + proto.STRING, + number=16, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=19, + ) + etag: str = proto.Field( + proto.STRING, + number=99, + ) + + +class EventFilter(proto.Message): + r"""Filters events based on exact matches on the CloudEvents + attributes. + + Attributes: + attribute (str): + Required. The name of a CloudEvents attribute. Currently, + only a subset of attributes are supported for filtering. You + can `retrieve a specific provider's supported event + types `__. + + All triggers MUST provide a filter for the 'type' attribute. + value (str): + Required. The value for the attribute. + operator (str): + Optional. The operator used for matching the events with the + value of the filter. If not specified, only events that have + an exact key-value pair specified in the filter are matched. + The allowed values are ``path_pattern`` and + ``match-path-pattern``. ``path_pattern`` is only allowed for + GCFv1 triggers. + """ + + attribute: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + operator: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StateCondition(proto.Message): + r"""A condition that is part of the trigger state computation. + + Attributes: + code (google.rpc.code_pb2.Code): + The canonical code of the condition. + message (str): + Human-readable message. + """ + + code: code_pb2.Code = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + message: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Destination(proto.Message): + r"""Represents a target of an invocation over HTTP. + + 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: + cloud_run (google.cloud.eventarc_v1.types.CloudRun): + Cloud Run fully-managed resource that + receives the events. The resource should be in + the same project as the trigger. + + This field is a member of `oneof`_ ``descriptor``. + cloud_function (str): + The Cloud Function resource name. Cloud Functions V1 and V2 + are supported. Format: + ``projects/{project}/locations/{location}/functions/{function}`` + + This is a read-only field. Creating Cloud Functions V1/V2 + triggers is only supported via the Cloud Functions product. + An error will be returned if the user sets this value. + + This field is a member of `oneof`_ ``descriptor``. + gke (google.cloud.eventarc_v1.types.GKE): + A GKE service capable of receiving events. + The service should be running in the same + project as the trigger. + + This field is a member of `oneof`_ ``descriptor``. + workflow (str): + The resource name of the Workflow whose Executions are + triggered by the events. The Workflow resource should be + deployed in the same project as the trigger. Format: + ``projects/{project}/locations/{location}/workflows/{workflow}`` + + This field is a member of `oneof`_ ``descriptor``. + http_endpoint (google.cloud.eventarc_v1.types.HttpEndpoint): + An HTTP endpoint destination described by an + URI. + + This field is a member of `oneof`_ ``descriptor``. + network_config (google.cloud.eventarc_v1.types.NetworkConfig): + Optional. Network config is used to configure + how Eventarc resolves and connect to a + destination. This should only be used with + HttpEndpoint destination type. + """ + + cloud_run: 'CloudRun' = proto.Field( + proto.MESSAGE, + number=1, + oneof='descriptor', + message='CloudRun', + ) + cloud_function: str = proto.Field( + proto.STRING, + number=2, + oneof='descriptor', + ) + gke: 'GKE' = proto.Field( + proto.MESSAGE, + number=3, + oneof='descriptor', + message='GKE', + ) + workflow: str = proto.Field( + proto.STRING, + number=4, + oneof='descriptor', + ) + http_endpoint: 'HttpEndpoint' = proto.Field( + proto.MESSAGE, + number=5, + oneof='descriptor', + message='HttpEndpoint', + ) + network_config: gce_network_config.NetworkConfig = proto.Field( + proto.MESSAGE, + number=6, + message=gce_network_config.NetworkConfig, + ) + + +class Transport(proto.Message): + r"""Represents the transport intermediaries created for the + trigger to deliver events. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pubsub (google.cloud.eventarc_v1.types.Pubsub): + The Pub/Sub topic and subscription used by + Eventarc as a transport intermediary. + + This field is a member of `oneof`_ ``intermediary``. + """ + + pubsub: 'Pubsub' = proto.Field( + proto.MESSAGE, + number=1, + oneof='intermediary', + message='Pubsub', + ) + + +class CloudRun(proto.Message): + r"""Represents a Cloud Run destination. + + Attributes: + service (str): + Required. The name of the Cloud Run service + being addressed. See + https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services. + + Only services located in the same project as the + trigger object can be addressed. + path (str): + Optional. The relative path on the Cloud Run + service the events should be sent to. + + The value must conform to the definition of a + URI path segment (section 3.3 of RFC2396). + Examples: "/route", "route", "route/subroute". + region (str): + Required. The region the Cloud Run service is + deployed in. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + path: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GKE(proto.Message): + r"""Represents a GKE destination. + + Attributes: + cluster (str): + Required. The name of the cluster the GKE + service is running in. The cluster must be + running in the same project as the trigger being + created. + location (str): + Required. The name of the Google Compute + Engine in which the cluster resides, which can + either be compute zone (for example, + us-central1-a) for the zonal clusters or region + (for example, us-central1) for regional + clusters. + namespace (str): + Required. The namespace the GKE service is + running in. + service (str): + Required. Name of the GKE service. + path (str): + Optional. The relative path on the GKE + service the events should be sent to. + + The value must conform to the definition of a + URI path segment (section 3.3 of RFC2396). + Examples: "/route", "route", "route/subroute". + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + namespace: str = proto.Field( + proto.STRING, + number=3, + ) + service: str = proto.Field( + proto.STRING, + number=4, + ) + path: str = proto.Field( + proto.STRING, + number=5, + ) + + +class Pubsub(proto.Message): + r"""Represents a Pub/Sub transport. + + Attributes: + topic (str): + Optional. The name of the Pub/Sub topic created and managed + by Eventarc as a transport for the event delivery. Format: + ``projects/{PROJECT_ID}/topics/{TOPIC_NAME}``. + + You can set an existing topic for triggers of the type + ``google.cloud.pubsub.topic.v1.messagePublished``. The topic + you provide here is not deleted by Eventarc at trigger + deletion. + subscription (str): + Output only. The name of the Pub/Sub subscription created + and managed by Eventarc as a transport for the event + delivery. Format: + ``projects/{PROJECT_ID}/subscriptions/{SUBSCRIPTION_NAME}``. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + subscription: str = proto.Field( + proto.STRING, + number=2, + ) + + +class HttpEndpoint(proto.Message): + r"""Represents a HTTP endpoint destination. + + Attributes: + uri (str): + Required. The URI of the HTTP enpdoint. + + The value must be a RFC2396 URI string. Examples: + ``http://10.10.10.8:80/route``, + ``http://svc.us-central1.p.local:8080/``. Only HTTP and + HTTPS protocols are supported. The host can be either a + static IP addressable from the VPC specified by the network + config, or an internal DNS hostname of the service + resolvable via Cloud DNS. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/mypy.ini b/owl-bot-staging/google-cloud-eventarc/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-eventarc/v1/noxfile.py b/owl-bot-staging/google-cloud-eventarc/v1/noxfile.py new file mode 100644 index 000000000000..685faed09bd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-eventarc' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/eventarc_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/eventarc_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py new file mode 100644 index 000000000000..ebff0154f662 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateChannel_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 eventarc_v1 + + +async def sample_create_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + channel = eventarc_v1.Channel() + channel.pubsub_topic = "pubsub_topic_value" + channel.name = "name_value" + + request = eventarc_v1.CreateChannelRequest( + parent="parent_value", + channel=channel, + channel_id="channel_id_value", + ) + + # Make the request + operation = client.create_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py new file mode 100644 index 000000000000..27908ff206e8 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateChannelConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateChannelConnection_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 eventarc_v1 + + +async def sample_create_channel_connection(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + channel_connection = eventarc_v1.ChannelConnection() + channel_connection.name = "name_value" + channel_connection.channel = "channel_value" + + request = eventarc_v1.CreateChannelConnectionRequest( + parent="parent_value", + channel_connection=channel_connection, + channel_connection_id="channel_connection_id_value", + ) + + # Make the request + operation = client.create_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateChannelConnection_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py new file mode 100644 index 000000000000..a4d3d5321f73 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateChannelConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateChannelConnection_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 eventarc_v1 + + +def sample_create_channel_connection(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + channel_connection = eventarc_v1.ChannelConnection() + channel_connection.name = "name_value" + channel_connection.channel = "channel_value" + + request = eventarc_v1.CreateChannelConnectionRequest( + parent="parent_value", + channel_connection=channel_connection, + channel_connection_id="channel_connection_id_value", + ) + + # Make the request + operation = client.create_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateChannelConnection_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py new file mode 100644 index 000000000000..de1b27e29efa --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateChannel_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 eventarc_v1 + + +def sample_create_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + channel = eventarc_v1.Channel() + channel.pubsub_topic = "pubsub_topic_value" + channel.name = "name_value" + + request = eventarc_v1.CreateChannelRequest( + parent="parent_value", + channel=channel, + channel_id="channel_id_value", + ) + + # Make the request + operation = client.create_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py new file mode 100644 index 000000000000..7b835166e5af --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateEnrollment_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 eventarc_v1 + + +async def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py new file mode 100644 index 000000000000..01f0e1796c2a --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateEnrollment_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 eventarc_v1 + + +def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py new file mode 100644 index 000000000000..7499aa595d93 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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 eventarc_v1 + + +async def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py new file mode 100644 index 000000000000..43c341d99c69 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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 eventarc_v1 + + +def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py new file mode 100644 index 000000000000..a36aac63a329 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateMessageBus_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 eventarc_v1 + + +async def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py new file mode 100644 index 000000000000..c57422a9805b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateMessageBus_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 eventarc_v1 + + +def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py new file mode 100644 index 000000000000..98e5c2bb46dc --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreatePipeline_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 eventarc_v1 + + +async def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreatePipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py new file mode 100644 index 000000000000..322d5cc27373 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreatePipeline_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 eventarc_v1 + + +def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreatePipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py new file mode 100644 index 000000000000..441e73fc34c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateTrigger_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 eventarc_v1 + + +async def sample_create_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + trigger = eventarc_v1.Trigger() + trigger.name = "name_value" + trigger.event_filters.attribute = "attribute_value" + trigger.event_filters.value = "value_value" + trigger.destination.cloud_run.service = "service_value" + trigger.destination.cloud_run.region = "region_value" + + request = eventarc_v1.CreateTriggerRequest( + parent="parent_value", + trigger=trigger, + trigger_id="trigger_id_value", + ) + + # Make the request + operation = client.create_trigger(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py new file mode 100644 index 000000000000..10b2fb5c6f95 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateTrigger_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 eventarc_v1 + + +def sample_create_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + trigger = eventarc_v1.Trigger() + trigger.name = "name_value" + trigger.event_filters.attribute = "attribute_value" + trigger.event_filters.value = "value_value" + trigger.destination.cloud_run.service = "service_value" + trigger.destination.cloud_run.region = "region_value" + + request = eventarc_v1.CreateTriggerRequest( + parent="parent_value", + trigger=trigger, + trigger_id="trigger_id_value", + ) + + # Make the request + operation = client.create_trigger(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py new file mode 100644 index 000000000000..9b4f036e29e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteChannel_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 eventarc_v1 + + +async def sample_delete_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py new file mode 100644 index 000000000000..92f3c64550fd --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteChannelConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteChannelConnection_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 eventarc_v1 + + +async def sample_delete_channel_connection(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelConnectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteChannelConnection_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py new file mode 100644 index 000000000000..c9a0a1e35252 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteChannelConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteChannelConnection_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 eventarc_v1 + + +def sample_delete_channel_connection(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelConnectionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel_connection(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteChannelConnection_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py new file mode 100644 index 000000000000..eea3bbe17056 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteChannel_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 eventarc_v1 + + +def sample_delete_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteChannelRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py new file mode 100644 index 000000000000..1452377cf60d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteEnrollment_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 eventarc_v1 + + +async def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py new file mode 100644 index 000000000000..85644a33732f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteEnrollment_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 eventarc_v1 + + +def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py new file mode 100644 index 000000000000..233bc8f978bc --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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 eventarc_v1 + + +async def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py new file mode 100644 index 000000000000..5036193f8da4 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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 eventarc_v1 + + +def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py new file mode 100644 index 000000000000..a9c638e332f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteMessageBus_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 eventarc_v1 + + +async def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py new file mode 100644 index 000000000000..2d73c87e36c1 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteMessageBus_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 eventarc_v1 + + +def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py new file mode 100644 index 000000000000..01ad54b6a7bb --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeletePipeline_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 eventarc_v1 + + +async def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeletePipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py new file mode 100644 index 000000000000..a74533f9472e --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeletePipeline_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 eventarc_v1 + + +def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeletePipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py new file mode 100644 index 000000000000..d8b0a8c4ca2c --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteTrigger_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 eventarc_v1 + + +async def sample_delete_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteTriggerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_trigger(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py new file mode 100644 index 000000000000..50ce9d7741ac --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteTrigger_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 eventarc_v1 + + +def sample_delete_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteTriggerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_trigger(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py new file mode 100644 index 000000000000..a2bdc034a30d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetChannel_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 eventarc_v1 + + +async def sample_get_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelRequest( + name="name_value", + ) + + # Make the request + response = await client.get_channel(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py new file mode 100644 index 000000000000..d1f83e2be2ff --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetChannelConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetChannelConnection_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 eventarc_v1 + + +async def sample_get_channel_connection(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelConnectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_channel_connection(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetChannelConnection_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py new file mode 100644 index 000000000000..e91dfb82ba94 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetChannelConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetChannelConnection_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 eventarc_v1 + + +def sample_get_channel_connection(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelConnectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_channel_connection(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetChannelConnection_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py new file mode 100644 index 000000000000..24f6e592ab2a --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetChannel_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 eventarc_v1 + + +def sample_get_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetChannelRequest( + name="name_value", + ) + + # Make the request + response = client.get_channel(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py new file mode 100644 index 000000000000..60b53a3c1f60 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetEnrollment_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 eventarc_v1 + + +async def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_enrollment(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py new file mode 100644 index 000000000000..5e5cfe0be1d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetEnrollment_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 eventarc_v1 + + +def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_enrollment(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py new file mode 100644 index 000000000000..4d6e6a7271d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetGoogleApiSource_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 eventarc_v1 + + +async def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_google_api_source(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py new file mode 100644 index 000000000000..d48db32727b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetGoogleApiSource_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 eventarc_v1 + + +def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_google_api_source(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py new file mode 100644 index 000000000000..43968fed3093 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGoogleChannelConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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 eventarc_v1 + + +async def sample_get_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleChannelConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_google_channel_config(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py new file mode 100644 index 000000000000..87cb63ab4e1f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGoogleChannelConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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 eventarc_v1 + + +def sample_get_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleChannelConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_google_channel_config(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py new file mode 100644 index 000000000000..f6fa28cec89e --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetMessageBus_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 eventarc_v1 + + +async def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message_bus(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py new file mode 100644 index 000000000000..f973b30f58a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetMessageBus_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 eventarc_v1 + + +def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = client.get_message_bus(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py new file mode 100644 index 000000000000..8b18437b7a6c --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetPipeline_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 eventarc_v1 + + +async def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_pipeline(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetPipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py new file mode 100644 index 000000000000..aaeabd978963 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetPipeline_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 eventarc_v1 + + +def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = client.get_pipeline(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetPipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py new file mode 100644 index 000000000000..ee87d696f717 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProvider +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetProvider_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 eventarc_v1 + + +async def sample_get_provider(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetProviderRequest( + name="name_value", + ) + + # Make the request + response = await client.get_provider(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetProvider_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py new file mode 100644 index 000000000000..9c19d1923ae4 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProvider +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetProvider_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 eventarc_v1 + + +def sample_get_provider(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetProviderRequest( + name="name_value", + ) + + # Make the request + response = client.get_provider(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetProvider_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py new file mode 100644 index 000000000000..36655bfbf3b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetTrigger_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 eventarc_v1 + + +async def sample_get_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetTriggerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_trigger(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py new file mode 100644 index 000000000000..8354eb167ebc --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetTrigger_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 eventarc_v1 + + +def sample_get_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetTriggerRequest( + name="name_value", + ) + + # Make the request + response = client.get_trigger(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py new file mode 100644 index 000000000000..24a4ac3b6b03 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListChannelConnections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListChannelConnections_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 eventarc_v1 + + +async def sample_list_channel_connections(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channel_connections(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListChannelConnections_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py new file mode 100644 index 000000000000..a8a5ec2ab3fd --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListChannelConnections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListChannelConnections_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 eventarc_v1 + + +def sample_list_channel_connections(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channel_connections(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListChannelConnections_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py new file mode 100644 index 000000000000..cb70db05a623 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListChannels +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListChannels_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 eventarc_v1 + + +async def sample_list_channels(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channels(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListChannels_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py new file mode 100644 index 000000000000..405dd6d39da9 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListChannels +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListChannels_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 eventarc_v1 + + +def sample_list_channels(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListChannelsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_channels(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListChannels_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py new file mode 100644 index 000000000000..a7b6705b45da --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEnrollments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListEnrollments_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 eventarc_v1 + + +async def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListEnrollments_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py new file mode 100644 index 000000000000..98c3c91cfb59 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEnrollments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListEnrollments_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 eventarc_v1 + + +def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListEnrollments_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py new file mode 100644 index 000000000000..d5190ae8997a --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGoogleApiSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListGoogleApiSources_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 eventarc_v1 + + +async def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListGoogleApiSources_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py new file mode 100644 index 000000000000..d5148cefa663 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGoogleApiSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListGoogleApiSources_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 eventarc_v1 + + +def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListGoogleApiSources_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py new file mode 100644 index 000000000000..43db0141b579 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessageBusEnrollments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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 eventarc_v1 + + +async def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py new file mode 100644 index 000000000000..54bc9ecb400a --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessageBusEnrollments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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 eventarc_v1 + + +def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py new file mode 100644 index 000000000000..97f05e8fafa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessageBuses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBuses_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 eventarc_v1 + + +async def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBuses_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py new file mode 100644 index 000000000000..1b41aa44c18f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessageBuses +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBuses_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 eventarc_v1 + + +def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBuses_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py new file mode 100644 index 000000000000..cbcbffb7ce4b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPipelines +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListPipelines_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 eventarc_v1 + + +async def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListPipelines_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py new file mode 100644 index 000000000000..7b1bcff80a83 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPipelines +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListPipelines_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 eventarc_v1 + + +def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListPipelines_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py new file mode 100644 index 000000000000..9b1a282ece1f --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProviders +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListProviders_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 eventarc_v1 + + +async def sample_list_providers(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_providers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListProviders_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py new file mode 100644 index 000000000000..bcaaa019d697 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProviders +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListProviders_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 eventarc_v1 + + +def sample_list_providers(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_providers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListProviders_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py new file mode 100644 index 000000000000..9878997a7732 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTriggers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListTriggers_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 eventarc_v1 + + +async def sample_list_triggers(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListTriggersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_triggers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListTriggers_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py new file mode 100644 index 000000000000..31558bea7a97 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTriggers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListTriggers_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 eventarc_v1 + + +def sample_list_triggers(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListTriggersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_triggers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListTriggers_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py new file mode 100644 index 000000000000..7e7c83e81fb7 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateChannel_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 eventarc_v1 + + +async def sample_update_channel(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateChannelRequest( + ) + + # Make the request + operation = client.update_channel(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py new file mode 100644 index 000000000000..8aaa9399228b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateChannel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateChannel_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 eventarc_v1 + + +def sample_update_channel(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateChannelRequest( + ) + + # Make the request + operation = client.update_channel(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py new file mode 100644 index 000000000000..a2aff56a7155 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateEnrollment_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 eventarc_v1 + + +async def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py new file mode 100644 index 000000000000..ca7e0c563a30 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEnrollment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateEnrollment_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 eventarc_v1 + + +def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py new file mode 100644 index 000000000000..68a50c679ac3 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_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 eventarc_v1 + + +async def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py new file mode 100644 index 000000000000..eea3efe7aa5b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGoogleApiSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_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 eventarc_v1 + + +def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py new file mode 100644 index 000000000000..ef74cb1afd0b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGoogleChannelConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_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 eventarc_v1 + + +async def sample_update_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_channel_config = eventarc_v1.GoogleChannelConfig() + google_channel_config.name = "name_value" + + request = eventarc_v1.UpdateGoogleChannelConfigRequest( + google_channel_config=google_channel_config, + ) + + # Make the request + response = await client.update_google_channel_config(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py new file mode 100644 index 000000000000..d20d7c495395 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGoogleChannelConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_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 eventarc_v1 + + +def sample_update_google_channel_config(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_channel_config = eventarc_v1.GoogleChannelConfig() + google_channel_config.name = "name_value" + + request = eventarc_v1.UpdateGoogleChannelConfigRequest( + google_channel_config=google_channel_config, + ) + + # Make the request + response = client.update_google_channel_config(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py new file mode 100644 index 000000000000..3c1b9e888f72 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateMessageBus_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 eventarc_v1 + + +async def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py new file mode 100644 index 000000000000..6aa6cb75b8bd --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMessageBus +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateMessageBus_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 eventarc_v1 + + +def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py new file mode 100644 index 000000000000..76c6fed7750b --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdatePipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdatePipeline_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 eventarc_v1 + + +async def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdatePipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py new file mode 100644 index 000000000000..2f70f5363ff2 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdatePipeline +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdatePipeline_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 eventarc_v1 + + +def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdatePipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py new file mode 100644 index 000000000000..a1e9fd81ea67 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateTrigger_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 eventarc_v1 + + +async def sample_update_trigger(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateTriggerRequest( + ) + + # Make the request + operation = client.update_trigger(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py new file mode 100644 index 000000000000..ba49e673d74c --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTrigger +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateTrigger_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 eventarc_v1 + + +def sample_update_trigger(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateTriggerRequest( + ) + + # Make the request + operation = client.update_trigger(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json new file mode 100644 index 000000000000..c94a230c3122 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json @@ -0,0 +1,6510 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.eventarc.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-eventarc", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateChannelConnectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel_connection", + "type": "google.cloud.eventarc_v1.types.ChannelConnection" + }, + { + "name": "channel_connection_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_channel_connection" + }, + "description": "Sample for CreateChannelConnection", + "file": "eventarc_v1_generated_eventarc_create_channel_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateChannelConnection_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_channel_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateChannelConnectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel_connection", + "type": "google.cloud.eventarc_v1.types.ChannelConnection" + }, + { + "name": "channel_connection_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_channel_connection" + }, + "description": "Sample for CreateChannelConnection", + "file": "eventarc_v1_generated_eventarc_create_channel_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateChannelConnection_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_channel_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateChannelRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel", + "type": "google.cloud.eventarc_v1.types.Channel" + }, + { + "name": "channel_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_channel" + }, + "description": "Sample for CreateChannel", + "file": "eventarc_v1_generated_eventarc_create_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateChannel_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateChannelRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "channel", + "type": "google.cloud.eventarc_v1.types.Channel" + }, + { + "name": "channel_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_channel" + }, + "description": "Sample for CreateChannel", + "file": "eventarc_v1_generated_eventarc_create_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateChannel_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateEnrollmentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" + }, + { + "name": "enrollment_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_enrollment" + }, + "description": "Sample for CreateEnrollment", + "file": "eventarc_v1_generated_eventarc_create_enrollment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateEnrollment_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_enrollment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateEnrollmentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" + }, + { + "name": "enrollment_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_enrollment" + }, + "description": "Sample for CreateEnrollment", + "file": "eventarc_v1_generated_eventarc_create_enrollment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateEnrollment_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_enrollment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "google_api_source_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_google_api_source" + }, + "description": "Sample for CreateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_create_google_api_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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": "eventarc_v1_generated_eventarc_create_google_api_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "google_api_source_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_google_api_source" + }, + "description": "Sample for CreateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_create_google_api_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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": "eventarc_v1_generated_eventarc_create_google_api_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateMessageBusRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" + }, + { + "name": "message_bus_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_message_bus" + }, + "description": "Sample for CreateMessageBus", + "file": "eventarc_v1_generated_eventarc_create_message_bus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateMessageBus_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": "eventarc_v1_generated_eventarc_create_message_bus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateMessageBusRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" + }, + { + "name": "message_bus_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_message_bus" + }, + "description": "Sample for CreateMessageBus", + "file": "eventarc_v1_generated_eventarc_create_message_bus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateMessageBus_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": "eventarc_v1_generated_eventarc_create_message_bus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreatePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreatePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreatePipelineRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" + }, + { + "name": "pipeline_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_pipeline" + }, + "description": "Sample for CreatePipeline", + "file": "eventarc_v1_generated_eventarc_create_pipeline_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreatePipeline_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": "eventarc_v1_generated_eventarc_create_pipeline_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreatePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreatePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreatePipelineRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" + }, + { + "name": "pipeline_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_pipeline" + }, + "description": "Sample for CreatePipeline", + "file": "eventarc_v1_generated_eventarc_create_pipeline_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreatePipeline_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": "eventarc_v1_generated_eventarc_create_pipeline_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "trigger", + "type": "google.cloud.eventarc_v1.types.Trigger" + }, + { + "name": "trigger_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_trigger" + }, + "description": "Sample for CreateTrigger", + "file": "eventarc_v1_generated_eventarc_create_trigger_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_async", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_trigger_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "CreateTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "trigger", + "type": "google.cloud.eventarc_v1.types.Trigger" + }, + { + "name": "trigger_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_trigger" + }, + "description": "Sample for CreateTrigger", + "file": "eventarc_v1_generated_eventarc_create_trigger_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_sync", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_create_trigger_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_channel_connection" + }, + "description": "Sample for DeleteChannelConnection", + "file": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_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": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_channel_connection" + }, + "description": "Sample for DeleteChannelConnection", + "file": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_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": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_channel" + }, + "description": "Sample for DeleteChannel", + "file": "eventarc_v1_generated_eventarc_delete_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_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": "eventarc_v1_generated_eventarc_delete_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_channel" + }, + "description": "Sample for DeleteChannel", + "file": "eventarc_v1_generated_eventarc_delete_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_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": "eventarc_v1_generated_eventarc_delete_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteEnrollmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_enrollment" + }, + "description": "Sample for DeleteEnrollment", + "file": "eventarc_v1_generated_eventarc_delete_enrollment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteEnrollment_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": "eventarc_v1_generated_eventarc_delete_enrollment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteEnrollmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_enrollment" + }, + "description": "Sample for DeleteEnrollment", + "file": "eventarc_v1_generated_eventarc_delete_enrollment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteEnrollment_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": "eventarc_v1_generated_eventarc_delete_enrollment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_google_api_source" + }, + "description": "Sample for DeleteGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_delete_google_api_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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": "eventarc_v1_generated_eventarc_delete_google_api_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_google_api_source" + }, + "description": "Sample for DeleteGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_delete_google_api_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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": "eventarc_v1_generated_eventarc_delete_google_api_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_message_bus" + }, + "description": "Sample for DeleteMessageBus", + "file": "eventarc_v1_generated_eventarc_delete_message_bus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteMessageBus_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": "eventarc_v1_generated_eventarc_delete_message_bus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_message_bus" + }, + "description": "Sample for DeleteMessageBus", + "file": "eventarc_v1_generated_eventarc_delete_message_bus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteMessageBus_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": "eventarc_v1_generated_eventarc_delete_message_bus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeletePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeletePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeletePipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_pipeline" + }, + "description": "Sample for DeletePipeline", + "file": "eventarc_v1_generated_eventarc_delete_pipeline_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeletePipeline_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": "eventarc_v1_generated_eventarc_delete_pipeline_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeletePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeletePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeletePipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_pipeline" + }, + "description": "Sample for DeletePipeline", + "file": "eventarc_v1_generated_eventarc_delete_pipeline_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeletePipeline_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": "eventarc_v1_generated_eventarc_delete_pipeline_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "allow_missing", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_trigger" + }, + "description": "Sample for DeleteTrigger", + "file": "eventarc_v1_generated_eventarc_delete_trigger_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_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": "eventarc_v1_generated_eventarc_delete_trigger_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "allow_missing", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_trigger" + }, + "description": "Sample for DeleteTrigger", + "file": "eventarc_v1_generated_eventarc_delete_trigger_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_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": "eventarc_v1_generated_eventarc_delete_trigger_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", + "shortName": "get_channel_connection" + }, + "description": "Sample for GetChannelConnection", + "file": "eventarc_v1_generated_eventarc_get_channel_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_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": "eventarc_v1_generated_eventarc_get_channel_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", + "shortName": "get_channel_connection" + }, + "description": "Sample for GetChannelConnection", + "file": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_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": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Channel", + "shortName": "get_channel" + }, + "description": "Sample for GetChannel", + "file": "eventarc_v1_generated_eventarc_get_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_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": "eventarc_v1_generated_eventarc_get_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Channel", + "shortName": "get_channel" + }, + "description": "Sample for GetChannel", + "file": "eventarc_v1_generated_eventarc_get_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_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": "eventarc_v1_generated_eventarc_get_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetEnrollmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Enrollment", + "shortName": "get_enrollment" + }, + "description": "Sample for GetEnrollment", + "file": "eventarc_v1_generated_eventarc_get_enrollment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetEnrollment_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": "eventarc_v1_generated_eventarc_get_enrollment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetEnrollmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Enrollment", + "shortName": "get_enrollment" + }, + "description": "Sample for GetEnrollment", + "file": "eventarc_v1_generated_eventarc_get_enrollment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetEnrollment_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": "eventarc_v1_generated_eventarc_get_enrollment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleApiSource", + "shortName": "get_google_api_source" + }, + "description": "Sample for GetGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_get_google_api_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleApiSource_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": "eventarc_v1_generated_eventarc_get_google_api_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleApiSource", + "shortName": "get_google_api_source" + }, + "description": "Sample for GetGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_get_google_api_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleApiSource_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": "eventarc_v1_generated_eventarc_get_google_api_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_channel_config", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleChannelConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "get_google_channel_config" + }, + "description": "Sample for GetGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_channel_config", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleChannelConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "get_google_channel_config" + }, + "description": "Sample for GetGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.MessageBus", + "shortName": "get_message_bus" + }, + "description": "Sample for GetMessageBus", + "file": "eventarc_v1_generated_eventarc_get_message_bus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetMessageBus_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": "eventarc_v1_generated_eventarc_get_message_bus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.MessageBus", + "shortName": "get_message_bus" + }, + "description": "Sample for GetMessageBus", + "file": "eventarc_v1_generated_eventarc_get_message_bus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetMessageBus_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": "eventarc_v1_generated_eventarc_get_message_bus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetPipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetPipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetPipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Pipeline", + "shortName": "get_pipeline" + }, + "description": "Sample for GetPipeline", + "file": "eventarc_v1_generated_eventarc_get_pipeline_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetPipeline_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": "eventarc_v1_generated_eventarc_get_pipeline_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetPipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetPipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetPipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Pipeline", + "shortName": "get_pipeline" + }, + "description": "Sample for GetPipeline", + "file": "eventarc_v1_generated_eventarc_get_pipeline_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetPipeline_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": "eventarc_v1_generated_eventarc_get_pipeline_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_provider", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetProviderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Provider", + "shortName": "get_provider" + }, + "description": "Sample for GetProvider", + "file": "eventarc_v1_generated_eventarc_get_provider_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_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": "eventarc_v1_generated_eventarc_get_provider_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_provider", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetProviderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Provider", + "shortName": "get_provider" + }, + "description": "Sample for GetProvider", + "file": "eventarc_v1_generated_eventarc_get_provider_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_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": "eventarc_v1_generated_eventarc_get_provider_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Trigger", + "shortName": "get_trigger" + }, + "description": "Sample for GetTrigger", + "file": "eventarc_v1_generated_eventarc_get_trigger_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_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": "eventarc_v1_generated_eventarc_get_trigger_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Trigger", + "shortName": "get_trigger" + }, + "description": "Sample for GetTrigger", + "file": "eventarc_v1_generated_eventarc_get_trigger_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_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": "eventarc_v1_generated_eventarc_get_trigger_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channel_connections", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannelConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsAsyncPager", + "shortName": "list_channel_connections" + }, + "description": "Sample for ListChannelConnections", + "file": "eventarc_v1_generated_eventarc_list_channel_connections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_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": "eventarc_v1_generated_eventarc_list_channel_connections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channel_connections", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannelConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsPager", + "shortName": "list_channel_connections" + }, + "description": "Sample for ListChannelConnections", + "file": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_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": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channels", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannels" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsAsyncPager", + "shortName": "list_channels" + }, + "description": "Sample for ListChannels", + "file": "eventarc_v1_generated_eventarc_list_channels_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_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": "eventarc_v1_generated_eventarc_list_channels_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channels", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannels" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsPager", + "shortName": "list_channels" + }, + "description": "Sample for ListChannels", + "file": "eventarc_v1_generated_eventarc_list_channels_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_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": "eventarc_v1_generated_eventarc_list_channels_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsAsyncPager", + "shortName": "list_enrollments" + }, + "description": "Sample for ListEnrollments", + "file": "eventarc_v1_generated_eventarc_list_enrollments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListEnrollments_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": "eventarc_v1_generated_eventarc_list_enrollments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsPager", + "shortName": "list_enrollments" + }, + "description": "Sample for ListEnrollments", + "file": "eventarc_v1_generated_eventarc_list_enrollments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListEnrollments_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": "eventarc_v1_generated_eventarc_list_enrollments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_google_api_sources", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListGoogleApiSources", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListGoogleApiSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesAsyncPager", + "shortName": "list_google_api_sources" + }, + "description": "Sample for ListGoogleApiSources", + "file": "eventarc_v1_generated_eventarc_list_google_api_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListGoogleApiSources_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": "eventarc_v1_generated_eventarc_list_google_api_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_google_api_sources", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListGoogleApiSources", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListGoogleApiSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesPager", + "shortName": "list_google_api_sources" + }, + "description": "Sample for ListGoogleApiSources", + "file": "eventarc_v1_generated_eventarc_list_google_api_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListGoogleApiSources_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": "eventarc_v1_generated_eventarc_list_google_api_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_message_bus_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBusEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBusEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsAsyncPager", + "shortName": "list_message_bus_enrollments" + }, + "description": "Sample for ListMessageBusEnrollments", + "file": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_message_bus_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBusEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBusEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsPager", + "shortName": "list_message_bus_enrollments" + }, + "description": "Sample for ListMessageBusEnrollments", + "file": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_message_buses", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBuses", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBuses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesAsyncPager", + "shortName": "list_message_buses" + }, + "description": "Sample for ListMessageBuses", + "file": "eventarc_v1_generated_eventarc_list_message_buses_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBuses_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": "eventarc_v1_generated_eventarc_list_message_buses_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_message_buses", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBuses", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBuses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesPager", + "shortName": "list_message_buses" + }, + "description": "Sample for ListMessageBuses", + "file": "eventarc_v1_generated_eventarc_list_message_buses_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBuses_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": "eventarc_v1_generated_eventarc_list_message_buses_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_pipelines", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListPipelines", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListPipelines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListPipelinesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesAsyncPager", + "shortName": "list_pipelines" + }, + "description": "Sample for ListPipelines", + "file": "eventarc_v1_generated_eventarc_list_pipelines_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListPipelines_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": "eventarc_v1_generated_eventarc_list_pipelines_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_pipelines", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListPipelines", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListPipelines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListPipelinesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesPager", + "shortName": "list_pipelines" + }, + "description": "Sample for ListPipelines", + "file": "eventarc_v1_generated_eventarc_list_pipelines_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListPipelines_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": "eventarc_v1_generated_eventarc_list_pipelines_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_providers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersAsyncPager", + "shortName": "list_providers" + }, + "description": "Sample for ListProviders", + "file": "eventarc_v1_generated_eventarc_list_providers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_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": "eventarc_v1_generated_eventarc_list_providers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_providers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersPager", + "shortName": "list_providers" + }, + "description": "Sample for ListProviders", + "file": "eventarc_v1_generated_eventarc_list_providers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_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": "eventarc_v1_generated_eventarc_list_providers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_triggers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListTriggers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersAsyncPager", + "shortName": "list_triggers" + }, + "description": "Sample for ListTriggers", + "file": "eventarc_v1_generated_eventarc_list_triggers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_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": "eventarc_v1_generated_eventarc_list_triggers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_triggers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListTriggers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersPager", + "shortName": "list_triggers" + }, + "description": "Sample for ListTriggers", + "file": "eventarc_v1_generated_eventarc_list_triggers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_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": "eventarc_v1_generated_eventarc_list_triggers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" + }, + { + "name": "channel", + "type": "google.cloud.eventarc_v1.types.Channel" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_channel" + }, + "description": "Sample for UpdateChannel", + "file": "eventarc_v1_generated_eventarc_update_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" + }, + { + "name": "channel", + "type": "google.cloud.eventarc_v1.types.Channel" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_channel" + }, + "description": "Sample for UpdateChannel", + "file": "eventarc_v1_generated_eventarc_update_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateEnrollmentRequest" + }, + { + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_enrollment" + }, + "description": "Sample for UpdateEnrollment", + "file": "eventarc_v1_generated_eventarc_update_enrollment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateEnrollment_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": "eventarc_v1_generated_eventarc_update_enrollment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateEnrollmentRequest" + }, + { + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_enrollment" + }, + "description": "Sample for UpdateEnrollment", + "file": "eventarc_v1_generated_eventarc_update_enrollment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateEnrollment_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": "eventarc_v1_generated_eventarc_update_enrollment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_google_api_source" + }, + "description": "Sample for UpdateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_update_google_api_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_google_api_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_google_api_source" + }, + "description": "Sample for UpdateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_update_google_api_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_google_api_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_channel_config", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateGoogleChannelConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" + }, + { + "name": "google_channel_config", + "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "update_google_channel_config" + }, + "description": "Sample for UpdateGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_channel_config", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateGoogleChannelConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" + }, + { + "name": "google_channel_config", + "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "update_google_channel_config" + }, + "description": "Sample for UpdateGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateMessageBusRequest" + }, + { + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_message_bus" + }, + "description": "Sample for UpdateMessageBus", + "file": "eventarc_v1_generated_eventarc_update_message_bus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateMessageBus_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_message_bus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateMessageBusRequest" + }, + { + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_message_bus" + }, + "description": "Sample for UpdateMessageBus", + "file": "eventarc_v1_generated_eventarc_update_message_bus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateMessageBus_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_message_bus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdatePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdatePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdatePipelineRequest" + }, + { + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_pipeline" + }, + "description": "Sample for UpdatePipeline", + "file": "eventarc_v1_generated_eventarc_update_pipeline_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdatePipeline_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_pipeline_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdatePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdatePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdatePipelineRequest" + }, + { + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_pipeline" + }, + "description": "Sample for UpdatePipeline", + "file": "eventarc_v1_generated_eventarc_update_pipeline_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdatePipeline_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_pipeline_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateTriggerRequest" + }, + { + "name": "trigger", + "type": "google.cloud.eventarc_v1.types.Trigger" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "allow_missing", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_trigger" + }, + "description": "Sample for UpdateTrigger", + "file": "eventarc_v1_generated_eventarc_update_trigger_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateTrigger_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_trigger_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateTriggerRequest" + }, + { + "name": "trigger", + "type": "google.cloud.eventarc_v1.types.Trigger" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "allow_missing", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_trigger" + }, + "description": "Sample for UpdateTrigger", + "file": "eventarc_v1_generated_eventarc_update_trigger_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateTrigger_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_trigger_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py b/owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py new file mode 100644 index 000000000000..b6e8d0a4c266 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py @@ -0,0 +1,214 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class eventarcCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_channel': ('parent', 'channel', 'channel_id', 'validate_only', ), + 'create_channel_connection': ('parent', 'channel_connection', 'channel_connection_id', ), + 'create_enrollment': ('parent', 'enrollment', 'enrollment_id', 'validate_only', ), + 'create_google_api_source': ('parent', 'google_api_source', 'google_api_source_id', 'validate_only', ), + 'create_message_bus': ('parent', 'message_bus', 'message_bus_id', 'validate_only', ), + 'create_pipeline': ('parent', 'pipeline', 'pipeline_id', 'validate_only', ), + 'create_trigger': ('parent', 'trigger', 'trigger_id', 'validate_only', ), + 'delete_channel': ('name', 'validate_only', ), + 'delete_channel_connection': ('name', ), + 'delete_enrollment': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_google_api_source': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_message_bus': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_pipeline': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_trigger': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'get_channel': ('name', ), + 'get_channel_connection': ('name', ), + 'get_enrollment': ('name', ), + 'get_google_api_source': ('name', ), + 'get_google_channel_config': ('name', ), + 'get_message_bus': ('name', ), + 'get_pipeline': ('name', ), + 'get_provider': ('name', ), + 'get_trigger': ('name', ), + 'list_channel_connections': ('parent', 'page_size', 'page_token', ), + 'list_channels': ('parent', 'page_size', 'page_token', 'order_by', ), + 'list_enrollments': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_google_api_sources': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_message_bus_enrollments': ('parent', 'page_size', 'page_token', ), + 'list_message_buses': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_pipelines': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_providers': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_triggers': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'update_channel': ('channel', 'update_mask', 'validate_only', ), + 'update_enrollment': ('enrollment', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_google_api_source': ('google_api_source', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_google_channel_config': ('google_channel_config', 'update_mask', ), + 'update_message_bus': ('message_bus', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_pipeline': ('pipeline', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_trigger': ('trigger', 'update_mask', 'allow_missing', 'validate_only', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=eventarcCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the eventarc client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/setup.py b/owl-bot-staging/google-cloud-eventarc/v1/setup.py new file mode 100644 index 000000000000..b54372e5e2d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-eventarc' + + +description = "Google Cloud Eventarc API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/eventarc/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py new file mode 100644 index 000000000000..5254d9ad52a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -0,0 +1,32779 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +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 client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.eventarc_v1.services.eventarc import EventarcAsyncClient +from google.cloud.eventarc_v1.services.eventarc import EventarcClient +from google.cloud.eventarc_v1.services.eventarc import pagers +from google.cloud.eventarc_v1.services.eventarc import transports +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel as gce_channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import network_config +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline +from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import trigger as gce_trigger +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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore +import google.auth + + +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 EventarcClient._get_default_mtls_endpoint(None) is None + assert EventarcClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EventarcClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EventarcClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EventarcClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EventarcClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert EventarcClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EventarcClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EventarcClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + EventarcClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert EventarcClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EventarcClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EventarcClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EventarcClient._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 EventarcClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert EventarcClient._get_client_cert_source(None, False) is None + assert EventarcClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EventarcClient._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 EventarcClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EventarcClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) +@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EventarcClient._DEFAULT_UNIVERSE + default_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EventarcClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EventarcClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EventarcClient.DEFAULT_MTLS_ENDPOINT + assert EventarcClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EventarcClient._get_api_endpoint(None, None, default_universe, "always") == EventarcClient.DEFAULT_MTLS_ENDPOINT + assert EventarcClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EventarcClient.DEFAULT_MTLS_ENDPOINT + assert EventarcClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EventarcClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EventarcClient._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 EventarcClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EventarcClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EventarcClient._get_universe_domain(None, None) == EventarcClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EventarcClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (EventarcClient, "grpc"), + (EventarcAsyncClient, "grpc_asyncio"), + (EventarcClient, "rest"), +]) +def test_eventarc_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 == ( + 'eventarc.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://eventarc.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EventarcGrpcTransport, "grpc"), + (transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EventarcRestTransport, "rest"), +]) +def test_eventarc_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", [ + (EventarcClient, "grpc"), + (EventarcAsyncClient, "grpc_asyncio"), + (EventarcClient, "rest"), +]) +def test_eventarc_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 == ( + 'eventarc.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://eventarc.googleapis.com' + ) + + +def test_eventarc_client_get_transport_class(): + transport = EventarcClient.get_transport_class() + available_transports = [ + transports.EventarcGrpcTransport, + transports.EventarcRestTransport, + ] + assert transport in available_transports + + transport = EventarcClient.get_transport_class("grpc") + assert transport == transports.EventarcGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EventarcClient, transports.EventarcGrpcTransport, "grpc"), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio"), + (EventarcClient, transports.EventarcRestTransport, "rest"), +]) +@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) +@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) +def test_eventarc_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(EventarcClient, '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(EventarcClient, '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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # 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", [ + (EventarcClient, transports.EventarcGrpcTransport, "grpc", "true"), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EventarcClient, transports.EventarcGrpcTransport, "grpc", "false"), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EventarcClient, transports.EventarcRestTransport, "rest", "true"), + (EventarcClient, transports.EventarcRestTransport, "rest", "false"), +]) +@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) +@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_eventarc_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", [ + EventarcClient, EventarcAsyncClient +]) +@mock.patch.object(EventarcClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EventarcClient)) +@mock.patch.object(EventarcAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EventarcAsyncClient)) +def test_eventarc_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + EventarcClient, EventarcAsyncClient +]) +@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) +@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) +def test_eventarc_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EventarcClient._DEFAULT_UNIVERSE + default_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EventarcClient._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", [ + (EventarcClient, transports.EventarcGrpcTransport, "grpc"), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio"), + (EventarcClient, transports.EventarcRestTransport, "rest"), +]) +def test_eventarc_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", [ + (EventarcClient, transports.EventarcGrpcTransport, "grpc", grpc_helpers), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EventarcClient, transports.EventarcRestTransport, "rest", None), +]) +def test_eventarc_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_eventarc_client_client_options_from_dict(): + with mock.patch('google.cloud.eventarc_v1.services.eventarc.transports.EventarcGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EventarcClient( + 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", [ + (EventarcClient, transports.EventarcGrpcTransport, "grpc", grpc_helpers), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_eventarc_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( + "eventarc.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="eventarc.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetTriggerRequest, + dict, +]) +def test_get_trigger(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trigger.Trigger( + name='name_value', + uid='uid_value', + service_account='service_account_value', + channel='channel_value', + event_data_content_type='event_data_content_type_value', + satisfies_pzs=True, + etag='etag_value', + ) + response = client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetTriggerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trigger.Trigger) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.service_account == 'service_account_value' + assert response.channel == 'channel_value' + assert response.event_data_content_type == 'event_data_content_type_value' + assert response.satisfies_pzs is True + assert response.etag == 'etag_value' + + +def test_get_trigger_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 = EventarcClient( + 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 = eventarc.GetTriggerRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_trigger(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetTriggerRequest( + name='name_value', + ) + +def test_get_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + request = {} + client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_trigger(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_trigger_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 = EventarcAsyncClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + await client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetTriggerRequest): + client = EventarcAsyncClient( + 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_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger( + name='name_value', + uid='uid_value', + service_account='service_account_value', + channel='channel_value', + event_data_content_type='event_data_content_type_value', + satisfies_pzs=True, + etag='etag_value', + )) + response = await client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetTriggerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trigger.Trigger) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.service_account == 'service_account_value' + assert response.channel == 'channel_value' + assert response.event_data_content_type == 'event_data_content_type_value' + assert response.satisfies_pzs is True + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_trigger_async_from_dict(): + await test_get_trigger_async(request_type=dict) + +def test_get_trigger_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetTriggerRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + call.return_value = trigger.Trigger() + client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_trigger_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetTriggerRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger()) + await client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_trigger_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trigger.Trigger() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_trigger( + name='name_value', + ) + + # 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_trigger_flattened_error(): + client = EventarcClient( + credentials=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_trigger( + eventarc.GetTriggerRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_trigger_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trigger.Trigger() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_trigger( + name='name_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_trigger_flattened_error_async(): + client = EventarcAsyncClient( + 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_trigger( + eventarc.GetTriggerRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListTriggersRequest, + dict, +]) +def test_list_triggers(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListTriggersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListTriggersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTriggersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_triggers_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 = EventarcClient( + 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 = eventarc.ListTriggersRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_triggers(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListTriggersRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + +def test_list_triggers_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 = EventarcClient( + 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_triggers 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_triggers] = mock_rpc + request = {} + client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_triggers(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_triggers_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 = EventarcAsyncClient( + 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_triggers 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_triggers] = mock_rpc + + request = {} + await client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_triggers(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_triggers_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListTriggersRequest): + client = EventarcAsyncClient( + 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_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListTriggersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTriggersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_triggers_async_from_dict(): + await test_list_triggers_async(request_type=dict) + +def test_list_triggers_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListTriggersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + call.return_value = eventarc.ListTriggersResponse() + client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_triggers_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListTriggersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse()) + await client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_triggers_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListTriggersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_triggers( + 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_triggers_flattened_error(): + client = EventarcClient( + credentials=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_triggers( + eventarc.ListTriggersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_triggers_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListTriggersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_triggers( + 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_triggers_flattened_error_async(): + client = EventarcAsyncClient( + 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_triggers( + eventarc.ListTriggersRequest(), + parent='parent_value', + ) + + +def test_list_triggers_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_triggers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + trigger.Trigger(), + ], + next_page_token='abc', + ), + eventarc.ListTriggersResponse( + triggers=[], + next_page_token='def', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + ], + next_page_token='ghi', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_triggers(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, trigger.Trigger) + for i in results) +def test_list_triggers_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_triggers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + trigger.Trigger(), + ], + next_page_token='abc', + ), + eventarc.ListTriggersResponse( + triggers=[], + next_page_token='def', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + ], + next_page_token='ghi', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + ], + ), + RuntimeError, + ) + pages = list(client.list_triggers(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_triggers_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + trigger.Trigger(), + ], + next_page_token='abc', + ), + eventarc.ListTriggersResponse( + triggers=[], + next_page_token='def', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + ], + next_page_token='ghi', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_triggers(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, trigger.Trigger) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_triggers_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + trigger.Trigger(), + ], + next_page_token='abc', + ), + eventarc.ListTriggersResponse( + triggers=[], + next_page_token='def', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + ], + next_page_token='ghi', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + ], + ), + 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_triggers(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", [ + eventarc.CreateTriggerRequest, + dict, +]) +def test_create_trigger(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateTriggerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_trigger_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 = EventarcClient( + 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 = eventarc.CreateTriggerRequest( + parent='parent_value', + trigger_id='trigger_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_trigger(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateTriggerRequest( + parent='parent_value', + trigger_id='trigger_id_value', + ) + +def test_create_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + request = {} + client.create_trigger(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_trigger(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_trigger_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 = EventarcAsyncClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + await client.create_trigger(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_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateTriggerRequest): + client = EventarcAsyncClient( + 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_trigger), + '__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_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateTriggerRequest() + 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_trigger_async_from_dict(): + await test_create_trigger_async(request_type=dict) + +def test_create_trigger_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateTriggerRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_trigger_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreateTriggerRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_trigger_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__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_trigger( + parent='parent_value', + trigger=gce_trigger.Trigger(name='name_value'), + trigger_id='trigger_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].trigger + mock_val = gce_trigger.Trigger(name='name_value') + assert arg == mock_val + arg = args[0].trigger_id + mock_val = 'trigger_id_value' + assert arg == mock_val + + +def test_create_trigger_flattened_error(): + client = EventarcClient( + credentials=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_trigger( + eventarc.CreateTriggerRequest(), + parent='parent_value', + trigger=gce_trigger.Trigger(name='name_value'), + trigger_id='trigger_id_value', + ) + +@pytest.mark.asyncio +async def test_create_trigger_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__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_trigger( + parent='parent_value', + trigger=gce_trigger.Trigger(name='name_value'), + trigger_id='trigger_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].trigger + mock_val = gce_trigger.Trigger(name='name_value') + assert arg == mock_val + arg = args[0].trigger_id + mock_val = 'trigger_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_trigger_flattened_error_async(): + client = EventarcAsyncClient( + 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_trigger( + eventarc.CreateTriggerRequest(), + parent='parent_value', + trigger=gce_trigger.Trigger(name='name_value'), + trigger_id='trigger_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateTriggerRequest, + dict, +]) +def test_update_trigger(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateTriggerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_trigger_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 = EventarcClient( + 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 = eventarc.UpdateTriggerRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_trigger(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateTriggerRequest( + ) + +def test_update_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + request = {} + client.update_trigger(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.update_trigger(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_trigger_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 = EventarcAsyncClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + await client.update_trigger(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.update_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateTriggerRequest): + client = EventarcAsyncClient( + 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_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateTriggerRequest() + 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_update_trigger_async_from_dict(): + await test_update_trigger_async(request_type=dict) + +def test_update_trigger_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateTriggerRequest() + + request.trigger.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'trigger.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_trigger_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdateTriggerRequest() + + request.trigger.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'trigger.name=name_value', + ) in kw['metadata'] + + +def test_update_trigger_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_trigger( + trigger=gce_trigger.Trigger(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + allow_missing=True, + ) + + # 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].trigger + mock_val = gce_trigger.Trigger(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].allow_missing + mock_val = True + assert arg == mock_val + + +def test_update_trigger_flattened_error(): + client = EventarcClient( + credentials=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_trigger( + eventarc.UpdateTriggerRequest(), + trigger=gce_trigger.Trigger(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + allow_missing=True, + ) + +@pytest.mark.asyncio +async def test_update_trigger_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_trigger( + trigger=gce_trigger.Trigger(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + allow_missing=True, + ) + + # 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].trigger + mock_val = gce_trigger.Trigger(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].allow_missing + mock_val = True + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_trigger_flattened_error_async(): + client = EventarcAsyncClient( + 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_trigger( + eventarc.UpdateTriggerRequest(), + trigger=gce_trigger.Trigger(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + allow_missing=True, + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteTriggerRequest, + dict, +]) +def test_delete_trigger(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteTriggerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_trigger_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 = EventarcClient( + 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 = eventarc.DeleteTriggerRequest( + 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_trigger), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_trigger(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteTriggerRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + request = {} + client.delete_trigger(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_trigger(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_trigger_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 = EventarcAsyncClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + await client.delete_trigger(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_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteTriggerRequest): + client = EventarcAsyncClient( + 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_trigger), + '__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_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteTriggerRequest() + 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_trigger_async_from_dict(): + await test_delete_trigger_async(request_type=dict) + +def test_delete_trigger_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteTriggerRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_trigger_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeleteTriggerRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_trigger_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__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_trigger( + name='name_value', + allow_missing=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].allow_missing + mock_val = True + assert arg == mock_val + + +def test_delete_trigger_flattened_error(): + client = EventarcClient( + credentials=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_trigger( + eventarc.DeleteTriggerRequest(), + name='name_value', + allow_missing=True, + ) + +@pytest.mark.asyncio +async def test_delete_trigger_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__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_trigger( + name='name_value', + allow_missing=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].allow_missing + mock_val = True + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_trigger_flattened_error_async(): + client = EventarcAsyncClient( + 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_trigger( + eventarc.DeleteTriggerRequest(), + name='name_value', + allow_missing=True, + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetChannelRequest, + dict, +]) +def test_get_channel(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel.Channel( + name='name_value', + uid='uid_value', + provider='provider_value', + state=channel.Channel.State.PENDING, + activation_token='activation_token_value', + crypto_key_name='crypto_key_name_value', + satisfies_pzs=True, + pubsub_topic='pubsub_topic_value', + ) + response = client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, channel.Channel) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.provider == 'provider_value' + assert response.state == channel.Channel.State.PENDING + assert response.activation_token == 'activation_token_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.satisfies_pzs is True + + +def test_get_channel_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 = EventarcClient( + 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 = eventarc.GetChannelRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_channel(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetChannelRequest( + name='name_value', + ) + +def test_get_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + request = {} + client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel(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_channel_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 = EventarcAsyncClient( + 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_channel 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_channel] = mock_rpc + + request = {} + await client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetChannelRequest): + client = EventarcAsyncClient( + 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_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel( + name='name_value', + uid='uid_value', + provider='provider_value', + state=channel.Channel.State.PENDING, + activation_token='activation_token_value', + crypto_key_name='crypto_key_name_value', + satisfies_pzs=True, + )) + response = await client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, channel.Channel) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.provider == 'provider_value' + assert response.state == channel.Channel.State.PENDING + assert response.activation_token == 'activation_token_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.satisfies_pzs is True + + +@pytest.mark.asyncio +async def test_get_channel_async_from_dict(): + await test_get_channel_async(request_type=dict) + +def test_get_channel_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetChannelRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + call.return_value = channel.Channel() + client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetChannelRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel()) + await client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel.Channel() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_channel( + name='name_value', + ) + + # 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_channel_flattened_error(): + client = EventarcClient( + credentials=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_channel( + eventarc.GetChannelRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_channel_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel.Channel() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_channel( + name='name_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_channel_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel( + eventarc.GetChannelRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListChannelsRequest, + dict, +]) +def test_list_channels(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListChannelsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListChannelsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_channels_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 = EventarcClient( + 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 = eventarc.ListChannelsRequest( + parent='parent_value', + page_token='page_token_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_channels), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_channels(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListChannelsRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + ) + +def test_list_channels_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 = EventarcClient( + 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_channels 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_channels] = mock_rpc + request = {} + client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channels(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_channels_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 = EventarcAsyncClient( + 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_channels 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_channels] = mock_rpc + + request = {} + await client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_channels(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_channels_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListChannelsRequest): + client = EventarcAsyncClient( + 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_channels), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListChannelsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_channels_async_from_dict(): + await test_list_channels_async(request_type=dict) + +def test_list_channels_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListChannelsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + call.return_value = eventarc.ListChannelsResponse() + client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channels_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListChannelsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse()) + await client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channels_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListChannelsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_channels( + 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_channels_flattened_error(): + client = EventarcClient( + credentials=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_channels( + eventarc.ListChannelsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_channels_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListChannelsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_channels( + 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_channels_flattened_error_async(): + client = EventarcAsyncClient( + 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_channels( + eventarc.ListChannelsRequest(), + parent='parent_value', + ) + + +def test_list_channels_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_channels), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + channel.Channel(), + ], + next_page_token='abc', + ), + eventarc.ListChannelsResponse( + channels=[], + next_page_token='def', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_channels(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, channel.Channel) + for i in results) +def test_list_channels_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_channels), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + channel.Channel(), + ], + next_page_token='abc', + ), + eventarc.ListChannelsResponse( + channels=[], + next_page_token='def', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + ], + ), + RuntimeError, + ) + pages = list(client.list_channels(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_channels_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + channel.Channel(), + ], + next_page_token='abc', + ), + eventarc.ListChannelsResponse( + channels=[], + next_page_token='def', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_channels(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, channel.Channel) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_channels_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + channel.Channel(), + ], + next_page_token='abc', + ), + eventarc.ListChannelsResponse( + channels=[], + next_page_token='def', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + ], + ), + 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_channels(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", [ + eventarc.CreateChannelRequest, + dict, +]) +def test_create_channel(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_channel_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 = EventarcClient( + 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 = eventarc.CreateChannelRequest( + parent='parent_value', + channel_id='channel_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_channel(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateChannelRequest( + parent='parent_value', + channel_id='channel_id_value', + ) + +def test_create_channel_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 = EventarcClient( + 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_channel_ 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_channel_] = mock_rpc + request = {} + client.create_channel(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_channel(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_channel_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 = EventarcAsyncClient( + 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_channel_ 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_channel_] = mock_rpc + + request = {} + await client.create_channel(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_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateChannelRequest): + client = EventarcAsyncClient( + 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_channel_), + '__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_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateChannelRequest() + 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_channel_async_from_dict(): + await test_create_channel_async(request_type=dict) + +def test_create_channel_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateChannelRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreateChannelRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__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_channel( + parent='parent_value', + channel=gce_channel.Channel(name='name_value'), + channel_id='channel_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].channel + mock_val = gce_channel.Channel(name='name_value') + assert arg == mock_val + arg = args[0].channel_id + mock_val = 'channel_id_value' + assert arg == mock_val + + +def test_create_channel_flattened_error(): + client = EventarcClient( + credentials=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_channel( + eventarc.CreateChannelRequest(), + parent='parent_value', + channel=gce_channel.Channel(name='name_value'), + channel_id='channel_id_value', + ) + +@pytest.mark.asyncio +async def test_create_channel_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__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_channel( + parent='parent_value', + channel=gce_channel.Channel(name='name_value'), + channel_id='channel_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].channel + mock_val = gce_channel.Channel(name='name_value') + assert arg == mock_val + arg = args[0].channel_id + mock_val = 'channel_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_channel_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel( + eventarc.CreateChannelRequest(), + parent='parent_value', + channel=gce_channel.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateChannelRequest, + dict, +]) +def test_update_channel(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_channel_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 = EventarcClient( + 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 = eventarc.UpdateChannelRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_channel(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateChannelRequest( + ) + +def test_update_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + request = {} + client.update_channel(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.update_channel(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_channel_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 = EventarcAsyncClient( + 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_channel 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_channel] = mock_rpc + + request = {} + await client.update_channel(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.update_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateChannelRequest): + client = EventarcAsyncClient( + 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_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateChannelRequest() + 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_update_channel_async_from_dict(): + await test_update_channel_async(request_type=dict) + +def test_update_channel_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateChannelRequest() + + request.channel.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'channel.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_channel_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdateChannelRequest() + + request.channel.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'channel.name=name_value', + ) in kw['metadata'] + + +def test_update_channel_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_channel( + channel=gce_channel.Channel(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].channel + mock_val = gce_channel.Channel(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_channel_flattened_error(): + client = EventarcClient( + credentials=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_channel( + eventarc.UpdateChannelRequest(), + channel=gce_channel.Channel(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_channel_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_channel( + channel=gce_channel.Channel(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].channel + mock_val = gce_channel.Channel(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_channel_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel( + eventarc.UpdateChannelRequest(), + channel=gce_channel.Channel(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteChannelRequest, + dict, +]) +def test_delete_channel(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteChannelRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_channel_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 = EventarcClient( + 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 = eventarc.DeleteChannelRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_channel(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteChannelRequest( + name='name_value', + ) + +def test_delete_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + request = {} + client.delete_channel(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_channel(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_channel_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 = EventarcAsyncClient( + 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_channel 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_channel] = mock_rpc + + request = {} + await client.delete_channel(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_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteChannelRequest): + client = EventarcAsyncClient( + 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_channel), + '__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_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteChannelRequest() + 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_channel_async_from_dict(): + await test_delete_channel_async(request_type=dict) + +def test_delete_channel_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteChannelRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeleteChannelRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__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_channel( + name='name_value', + ) + + # 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_channel_flattened_error(): + client = EventarcClient( + credentials=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_channel( + eventarc.DeleteChannelRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_channel_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__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_channel( + name='name_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_channel_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel( + eventarc.DeleteChannelRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetProviderRequest, + dict, +]) +def test_get_provider(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = discovery.Provider( + name='name_value', + display_name='display_name_value', + ) + response = client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetProviderRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, discovery.Provider) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_provider_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 = EventarcClient( + 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 = eventarc.GetProviderRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_provider(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetProviderRequest( + name='name_value', + ) + +def test_get_provider_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 = EventarcClient( + 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_provider 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_provider] = mock_rpc + request = {} + client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_provider(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_provider_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 = EventarcAsyncClient( + 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_provider 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_provider] = mock_rpc + + request = {} + await client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_provider(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_provider_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetProviderRequest): + client = EventarcAsyncClient( + 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_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetProviderRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, discovery.Provider) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_provider_async_from_dict(): + await test_get_provider_async(request_type=dict) + +def test_get_provider_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetProviderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + call.return_value = discovery.Provider() + client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_provider_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetProviderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider()) + await client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_provider_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = discovery.Provider() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_provider( + name='name_value', + ) + + # 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_provider_flattened_error(): + client = EventarcClient( + credentials=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_provider( + eventarc.GetProviderRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_provider_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = discovery.Provider() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_provider( + name='name_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_provider_flattened_error_async(): + client = EventarcAsyncClient( + 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_provider( + eventarc.GetProviderRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListProvidersRequest, + dict, +]) +def test_list_providers(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListProvidersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListProvidersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProvidersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_providers_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 = EventarcClient( + 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 = eventarc.ListProvidersRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_providers(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListProvidersRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + +def test_list_providers_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 = EventarcClient( + 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_providers 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_providers] = mock_rpc + request = {} + client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_providers(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_providers_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 = EventarcAsyncClient( + 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_providers 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_providers] = mock_rpc + + request = {} + await client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_providers(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_providers_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListProvidersRequest): + client = EventarcAsyncClient( + 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_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListProvidersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProvidersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_providers_async_from_dict(): + await test_list_providers_async(request_type=dict) + +def test_list_providers_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListProvidersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + call.return_value = eventarc.ListProvidersResponse() + client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_providers_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListProvidersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse()) + await client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_providers_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListProvidersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_providers( + 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_providers_flattened_error(): + client = EventarcClient( + credentials=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_providers( + eventarc.ListProvidersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_providers_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListProvidersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_providers( + 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_providers_flattened_error_async(): + client = EventarcAsyncClient( + 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_providers( + eventarc.ListProvidersRequest(), + parent='parent_value', + ) + + +def test_list_providers_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_providers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + discovery.Provider(), + ], + next_page_token='abc', + ), + eventarc.ListProvidersResponse( + providers=[], + next_page_token='def', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + ], + next_page_token='ghi', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_providers(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, discovery.Provider) + for i in results) +def test_list_providers_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_providers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + discovery.Provider(), + ], + next_page_token='abc', + ), + eventarc.ListProvidersResponse( + providers=[], + next_page_token='def', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + ], + next_page_token='ghi', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + ], + ), + RuntimeError, + ) + pages = list(client.list_providers(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_providers_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + discovery.Provider(), + ], + next_page_token='abc', + ), + eventarc.ListProvidersResponse( + providers=[], + next_page_token='def', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + ], + next_page_token='ghi', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_providers(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, discovery.Provider) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_providers_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + discovery.Provider(), + ], + next_page_token='abc', + ), + eventarc.ListProvidersResponse( + providers=[], + next_page_token='def', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + ], + next_page_token='ghi', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + ], + ), + 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_providers(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", [ + eventarc.GetChannelConnectionRequest, + dict, +]) +def test_get_channel_connection(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel_connection.ChannelConnection( + name='name_value', + uid='uid_value', + channel='channel_value', + activation_token='activation_token_value', + ) + response = client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetChannelConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_connection.ChannelConnection) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.channel == 'channel_value' + assert response.activation_token == 'activation_token_value' + + +def test_get_channel_connection_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 = EventarcClient( + 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 = eventarc.GetChannelConnectionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_channel_connection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetChannelConnectionRequest( + name='name_value', + ) + +def test_get_channel_connection_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 = EventarcClient( + 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_channel_connection 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_channel_connection] = mock_rpc + request = {} + client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel_connection(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_channel_connection_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 = EventarcAsyncClient( + 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_channel_connection 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_channel_connection] = mock_rpc + + request = {} + await client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_channel_connection(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_channel_connection_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetChannelConnectionRequest): + client = EventarcAsyncClient( + 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_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection( + name='name_value', + uid='uid_value', + channel='channel_value', + activation_token='activation_token_value', + )) + response = await client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetChannelConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_connection.ChannelConnection) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.channel == 'channel_value' + assert response.activation_token == 'activation_token_value' + + +@pytest.mark.asyncio +async def test_get_channel_connection_async_from_dict(): + await test_get_channel_connection_async(request_type=dict) + +def test_get_channel_connection_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetChannelConnectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + call.return_value = channel_connection.ChannelConnection() + client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_connection_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetChannelConnectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection()) + await client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_connection_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel_connection.ChannelConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_channel_connection( + name='name_value', + ) + + # 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_channel_connection_flattened_error(): + client = EventarcClient( + credentials=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_channel_connection( + eventarc.GetChannelConnectionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_channel_connection_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel_connection.ChannelConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_channel_connection( + name='name_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_channel_connection_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel_connection( + eventarc.GetChannelConnectionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListChannelConnectionsRequest, + dict, +]) +def test_list_channel_connections(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListChannelConnectionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListChannelConnectionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelConnectionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_channel_connections_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 = EventarcClient( + 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 = eventarc.ListChannelConnectionsRequest( + 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_channel_connections), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_channel_connections(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListChannelConnectionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_channel_connections_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 = EventarcClient( + 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_channel_connections 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_channel_connections] = mock_rpc + request = {} + client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channel_connections(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_channel_connections_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 = EventarcAsyncClient( + 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_channel_connections 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_channel_connections] = mock_rpc + + request = {} + await client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_channel_connections(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_channel_connections_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListChannelConnectionsRequest): + client = EventarcAsyncClient( + 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_channel_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListChannelConnectionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelConnectionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_channel_connections_async_from_dict(): + await test_list_channel_connections_async(request_type=dict) + +def test_list_channel_connections_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListChannelConnectionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + call.return_value = eventarc.ListChannelConnectionsResponse() + client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_connections_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListChannelConnectionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse()) + await client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_connections_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListChannelConnectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_channel_connections( + 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_channel_connections_flattened_error(): + client = EventarcClient( + credentials=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_channel_connections( + eventarc.ListChannelConnectionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_channel_connections_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListChannelConnectionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_channel_connections( + 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_channel_connections_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel_connections( + eventarc.ListChannelConnectionsRequest(), + parent='parent_value', + ) + + +def test_list_channel_connections_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_channel_connections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + next_page_token='abc', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[], + next_page_token='def', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_channel_connections(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, channel_connection.ChannelConnection) + for i in results) +def test_list_channel_connections_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_channel_connections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + next_page_token='abc', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[], + next_page_token='def', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + ), + RuntimeError, + ) + pages = list(client.list_channel_connections(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_channel_connections_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + next_page_token='abc', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[], + next_page_token='def', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_channel_connections(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, channel_connection.ChannelConnection) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_channel_connections_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + next_page_token='abc', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[], + next_page_token='def', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + ), + 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_channel_connections(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", [ + eventarc.CreateChannelConnectionRequest, + dict, +]) +def test_create_channel_connection(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateChannelConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_channel_connection_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 = EventarcClient( + 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 = eventarc.CreateChannelConnectionRequest( + parent='parent_value', + channel_connection_id='channel_connection_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_channel_connection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateChannelConnectionRequest( + parent='parent_value', + channel_connection_id='channel_connection_id_value', + ) + +def test_create_channel_connection_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 = EventarcClient( + 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_channel_connection 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_channel_connection] = mock_rpc + request = {} + client.create_channel_connection(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_channel_connection(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_channel_connection_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 = EventarcAsyncClient( + 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_channel_connection 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_channel_connection] = mock_rpc + + request = {} + await client.create_channel_connection(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_channel_connection(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_channel_connection_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateChannelConnectionRequest): + client = EventarcAsyncClient( + 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_channel_connection), + '__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_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateChannelConnectionRequest() + 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_channel_connection_async_from_dict(): + await test_create_channel_connection_async(request_type=dict) + +def test_create_channel_connection_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateChannelConnectionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_connection_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreateChannelConnectionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_connection_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__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_channel_connection( + parent='parent_value', + channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), + channel_connection_id='channel_connection_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].channel_connection + mock_val = gce_channel_connection.ChannelConnection(name='name_value') + assert arg == mock_val + arg = args[0].channel_connection_id + mock_val = 'channel_connection_id_value' + assert arg == mock_val + + +def test_create_channel_connection_flattened_error(): + client = EventarcClient( + credentials=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_channel_connection( + eventarc.CreateChannelConnectionRequest(), + parent='parent_value', + channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), + channel_connection_id='channel_connection_id_value', + ) + +@pytest.mark.asyncio +async def test_create_channel_connection_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__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_channel_connection( + parent='parent_value', + channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), + channel_connection_id='channel_connection_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].channel_connection + mock_val = gce_channel_connection.ChannelConnection(name='name_value') + assert arg == mock_val + arg = args[0].channel_connection_id + mock_val = 'channel_connection_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_channel_connection_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel_connection( + eventarc.CreateChannelConnectionRequest(), + parent='parent_value', + channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), + channel_connection_id='channel_connection_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteChannelConnectionRequest, + dict, +]) +def test_delete_channel_connection(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteChannelConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_channel_connection_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 = EventarcClient( + 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 = eventarc.DeleteChannelConnectionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_channel_connection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteChannelConnectionRequest( + name='name_value', + ) + +def test_delete_channel_connection_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 = EventarcClient( + 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_channel_connection 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_channel_connection] = mock_rpc + request = {} + client.delete_channel_connection(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_channel_connection(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_channel_connection_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 = EventarcAsyncClient( + 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_channel_connection 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_channel_connection] = mock_rpc + + request = {} + await client.delete_channel_connection(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_channel_connection(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_channel_connection_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteChannelConnectionRequest): + client = EventarcAsyncClient( + 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_channel_connection), + '__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_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteChannelConnectionRequest() + 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_channel_connection_async_from_dict(): + await test_delete_channel_connection_async(request_type=dict) + +def test_delete_channel_connection_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteChannelConnectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_channel_connection_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeleteChannelConnectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_channel_connection_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__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_channel_connection( + name='name_value', + ) + + # 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_channel_connection_flattened_error(): + client = EventarcClient( + credentials=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_channel_connection( + eventarc.DeleteChannelConnectionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_channel_connection_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__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_channel_connection( + name='name_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_channel_connection_flattened_error_async(): + client = EventarcAsyncClient( + 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_channel_connection( + eventarc.DeleteChannelConnectionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetGoogleChannelConfigRequest, + dict, +]) +def test_get_google_channel_config(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_name_value', + ) + response = client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetGoogleChannelConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, google_channel_config.GoogleChannelConfig) + assert response.name == 'name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +def test_get_google_channel_config_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 = EventarcClient( + 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 = eventarc.GetGoogleChannelConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_google_channel_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetGoogleChannelConfigRequest( + name='name_value', + ) + +def test_get_google_channel_config_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 = EventarcClient( + 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_google_channel_config 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_google_channel_config] = mock_rpc + request = {} + client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_channel_config(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_google_channel_config_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 = EventarcAsyncClient( + 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_google_channel_config 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_google_channel_config] = mock_rpc + + request = {} + await client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_google_channel_config(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_google_channel_config_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetGoogleChannelConfigRequest): + client = EventarcAsyncClient( + 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_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_name_value', + )) + response = await client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetGoogleChannelConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, google_channel_config.GoogleChannelConfig) + assert response.name == 'name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.asyncio +async def test_get_google_channel_config_async_from_dict(): + await test_get_google_channel_config_async(request_type=dict) + +def test_get_google_channel_config_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetGoogleChannelConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + call.return_value = google_channel_config.GoogleChannelConfig() + client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_google_channel_config_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetGoogleChannelConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig()) + await client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_google_channel_config_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = google_channel_config.GoogleChannelConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_google_channel_config( + name='name_value', + ) + + # 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_google_channel_config_flattened_error(): + client = EventarcClient( + credentials=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_google_channel_config( + eventarc.GetGoogleChannelConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_google_channel_config_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = google_channel_config.GoogleChannelConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_google_channel_config( + name='name_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_google_channel_config_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_channel_config( + eventarc.GetGoogleChannelConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateGoogleChannelConfigRequest, + dict, +]) +def test_update_google_channel_config(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gce_google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_name_value', + ) + response = client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateGoogleChannelConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) + assert response.name == 'name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +def test_update_google_channel_config_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 = EventarcClient( + 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 = eventarc.UpdateGoogleChannelConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_channel_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateGoogleChannelConfigRequest( + ) + +def test_update_google_channel_config_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 = EventarcClient( + 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_google_channel_config 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_google_channel_config] = mock_rpc + request = {} + client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_channel_config(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_google_channel_config_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 = EventarcAsyncClient( + 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_google_channel_config 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_google_channel_config] = mock_rpc + + request = {} + await client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_google_channel_config(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_google_channel_config_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateGoogleChannelConfigRequest): + client = EventarcAsyncClient( + 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_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_name_value', + )) + response = await client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateGoogleChannelConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) + assert response.name == 'name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.asyncio +async def test_update_google_channel_config_async_from_dict(): + await test_update_google_channel_config_async(request_type=dict) + +def test_update_google_channel_config_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateGoogleChannelConfigRequest() + + request.google_channel_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + call.return_value = gce_google_channel_config.GoogleChannelConfig() + client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_channel_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_google_channel_config_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdateGoogleChannelConfigRequest() + + request.google_channel_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig()) + await client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_channel_config.name=name_value', + ) in kw['metadata'] + + +def test_update_google_channel_config_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gce_google_channel_config.GoogleChannelConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_google_channel_config( + google_channel_config=gce_google_channel_config.GoogleChannelConfig(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].google_channel_config + mock_val = gce_google_channel_config.GoogleChannelConfig(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_google_channel_config_flattened_error(): + client = EventarcClient( + credentials=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_google_channel_config( + eventarc.UpdateGoogleChannelConfigRequest(), + google_channel_config=gce_google_channel_config.GoogleChannelConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_google_channel_config_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gce_google_channel_config.GoogleChannelConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_google_channel_config( + google_channel_config=gce_google_channel_config.GoogleChannelConfig(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].google_channel_config + mock_val = gce_google_channel_config.GoogleChannelConfig(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_google_channel_config_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_channel_config( + eventarc.UpdateGoogleChannelConfigRequest(), + google_channel_config=gce_google_channel_config.GoogleChannelConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetMessageBusRequest, + dict, +]) +def test_get_message_bus(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = message_bus.MessageBus( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + ) + response = client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, message_bus.MessageBus) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +def test_get_message_bus_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 = EventarcClient( + 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 = eventarc.GetMessageBusRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetMessageBusRequest( + name='name_value', + ) + +def test_get_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + request = {} + client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_message_bus(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_message_bus_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 = EventarcAsyncClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + await client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetMessageBusRequest): + client = EventarcAsyncClient( + 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_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + )) + response = await client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, message_bus.MessageBus) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.asyncio +async def test_get_message_bus_async_from_dict(): + await test_get_message_bus_async(request_type=dict) + +def test_get_message_bus_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetMessageBusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + call.return_value = message_bus.MessageBus() + client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_message_bus_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetMessageBusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus()) + await client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = message_bus.MessageBus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_message_bus( + name='name_value', + ) + + # 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_message_bus_flattened_error(): + client = EventarcClient( + credentials=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_message_bus( + eventarc.GetMessageBusRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = message_bus.MessageBus() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_message_bus( + name='name_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_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + 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_message_bus( + eventarc.GetMessageBusRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListMessageBusesRequest, + dict, +]) +def test_list_message_buses(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_message_buses_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 = EventarcClient( + 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 = eventarc.ListMessageBusesRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_message_buses(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListMessageBusesRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + +def test_list_message_buses_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 = EventarcClient( + 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_message_buses 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_message_buses] = mock_rpc + request = {} + client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_message_buses(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_message_buses_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 = EventarcAsyncClient( + 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_message_buses 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_message_buses] = mock_rpc + + request = {} + await client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_message_buses(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_message_buses_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListMessageBusesRequest): + client = EventarcAsyncClient( + 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_message_buses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_message_buses_async_from_dict(): + await test_list_message_buses_async(request_type=dict) + +def test_list_message_buses_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListMessageBusesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + call.return_value = eventarc.ListMessageBusesResponse() + client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_message_buses_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListMessageBusesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse()) + await client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_message_buses_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_message_buses( + 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_message_buses_flattened_error(): + client = EventarcClient( + credentials=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_message_buses( + eventarc.ListMessageBusesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_message_buses_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_message_buses( + 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_message_buses_flattened_error_async(): + client = EventarcAsyncClient( + 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_message_buses( + eventarc.ListMessageBusesRequest(), + parent='parent_value', + ) + + +def test_list_message_buses_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_message_buses), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token='def', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_message_buses(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, message_bus.MessageBus) + for i in results) +def test_list_message_buses_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_message_buses), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token='def', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, + ) + pages = list(client.list_message_buses(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_message_buses_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token='def', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_message_buses(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, message_bus.MessageBus) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_message_buses_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token='def', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + 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_message_buses(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", [ + eventarc.ListMessageBusEnrollmentsRequest, + dict, +]) +def test_list_message_bus_enrollments(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusEnrollmentsResponse( + enrollments=['enrollments_value'], + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusEnrollmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusEnrollmentsPager) + assert response.enrollments == ['enrollments_value'] + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_message_bus_enrollments_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 = EventarcClient( + 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 = eventarc.ListMessageBusEnrollmentsRequest( + 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_message_bus_enrollments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_message_bus_enrollments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListMessageBusEnrollmentsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_message_bus_enrollments_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 = EventarcClient( + 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_message_bus_enrollments 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_message_bus_enrollments] = mock_rpc + request = {} + client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_message_bus_enrollments(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_message_bus_enrollments_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 = EventarcAsyncClient( + 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_message_bus_enrollments 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_message_bus_enrollments] = mock_rpc + + request = {} + await client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_message_bus_enrollments(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_message_bus_enrollments_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListMessageBusEnrollmentsRequest): + client = EventarcAsyncClient( + 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_message_bus_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse( + enrollments=['enrollments_value'], + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusEnrollmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusEnrollmentsAsyncPager) + assert response.enrollments == ['enrollments_value'] + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async_from_dict(): + await test_list_message_bus_enrollments_async(request_type=dict) + +def test_list_message_bus_enrollments_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListMessageBusEnrollmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_message_bus_enrollments_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListMessageBusEnrollmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse()) + await client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_message_bus_enrollments_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_message_bus_enrollments( + 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_message_bus_enrollments_flattened_error(): + client = EventarcClient( + credentials=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_message_bus_enrollments( + eventarc.ListMessageBusEnrollmentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_message_bus_enrollments( + 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_message_bus_enrollments_flattened_error_async(): + client = EventarcAsyncClient( + 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_message_bus_enrollments( + eventarc.ListMessageBusEnrollmentsRequest(), + parent='parent_value', + ) + + +def test_list_message_bus_enrollments_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_message_bus_enrollments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_message_bus_enrollments(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, str) + for i in results) +def test_list_message_bus_enrollments_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_message_bus_enrollments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = list(client.list_message_bus_enrollments(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_message_bus_enrollments_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_message_bus_enrollments(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, str) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + 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_message_bus_enrollments(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", [ + eventarc.CreateMessageBusRequest, + dict, +]) +def test_create_message_bus(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_message_bus_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 = EventarcClient( + 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 = eventarc.CreateMessageBusRequest( + parent='parent_value', + message_bus_id='message_bus_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateMessageBusRequest( + parent='parent_value', + message_bus_id='message_bus_id_value', + ) + +def test_create_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + request = {} + client.create_message_bus(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_message_bus(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_message_bus_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 = EventarcAsyncClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + await client.create_message_bus(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_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateMessageBusRequest): + client = EventarcAsyncClient( + 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_message_bus), + '__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_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateMessageBusRequest() + 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_message_bus_async_from_dict(): + await test_create_message_bus_async(request_type=dict) + +def test_create_message_bus_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateMessageBusRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_message_bus_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreateMessageBusRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__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_message_bus( + parent='parent_value', + message_bus=gce_message_bus.MessageBus(name='name_value'), + message_bus_id='message_bus_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].message_bus + mock_val = gce_message_bus.MessageBus(name='name_value') + assert arg == mock_val + arg = args[0].message_bus_id + mock_val = 'message_bus_id_value' + assert arg == mock_val + + +def test_create_message_bus_flattened_error(): + client = EventarcClient( + credentials=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_message_bus( + eventarc.CreateMessageBusRequest(), + parent='parent_value', + message_bus=gce_message_bus.MessageBus(name='name_value'), + message_bus_id='message_bus_id_value', + ) + +@pytest.mark.asyncio +async def test_create_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__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_message_bus( + parent='parent_value', + message_bus=gce_message_bus.MessageBus(name='name_value'), + message_bus_id='message_bus_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].message_bus + mock_val = gce_message_bus.MessageBus(name='name_value') + assert arg == mock_val + arg = args[0].message_bus_id + mock_val = 'message_bus_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + 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_message_bus( + eventarc.CreateMessageBusRequest(), + parent='parent_value', + message_bus=gce_message_bus.MessageBus(name='name_value'), + message_bus_id='message_bus_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateMessageBusRequest, + dict, +]) +def test_update_message_bus(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_message_bus_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 = EventarcClient( + 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 = eventarc.UpdateMessageBusRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateMessageBusRequest( + ) + +def test_update_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + request = {} + client.update_message_bus(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.update_message_bus(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_message_bus_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 = EventarcAsyncClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + await client.update_message_bus(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.update_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateMessageBusRequest): + client = EventarcAsyncClient( + 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_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateMessageBusRequest() + 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_update_message_bus_async_from_dict(): + await test_update_message_bus_async(request_type=dict) + +def test_update_message_bus_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateMessageBusRequest() + + request.message_bus.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'message_bus.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_message_bus_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdateMessageBusRequest() + + request.message_bus.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'message_bus.name=name_value', + ) in kw['metadata'] + + +def test_update_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_message_bus( + message_bus=gce_message_bus.MessageBus(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].message_bus + mock_val = gce_message_bus.MessageBus(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_message_bus_flattened_error(): + client = EventarcClient( + credentials=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_message_bus( + eventarc.UpdateMessageBusRequest(), + message_bus=gce_message_bus.MessageBus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_message_bus( + message_bus=gce_message_bus.MessageBus(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].message_bus + mock_val = gce_message_bus.MessageBus(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_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + 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_message_bus( + eventarc.UpdateMessageBusRequest(), + message_bus=gce_message_bus.MessageBus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteMessageBusRequest, + dict, +]) +def test_delete_message_bus(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_message_bus_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 = EventarcClient( + 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 = eventarc.DeleteMessageBusRequest( + 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_message_bus), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteMessageBusRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + request = {} + client.delete_message_bus(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_message_bus(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_message_bus_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 = EventarcAsyncClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + await client.delete_message_bus(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_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteMessageBusRequest): + client = EventarcAsyncClient( + 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_message_bus), + '__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_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteMessageBusRequest() + 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_message_bus_async_from_dict(): + await test_delete_message_bus_async(request_type=dict) + +def test_delete_message_bus_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteMessageBusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_message_bus_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeleteMessageBusRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__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_message_bus( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + + +def test_delete_message_bus_flattened_error(): + client = EventarcClient( + credentials=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_message_bus( + eventarc.DeleteMessageBusRequest(), + name='name_value', + etag='etag_value', + ) + +@pytest.mark.asyncio +async def test_delete_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__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_message_bus( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + 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_message_bus( + eventarc.DeleteMessageBusRequest(), + name='name_value', + etag='etag_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetEnrollmentRequest, + dict, +]) +def test_get_enrollment(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = enrollment.Enrollment( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + cel_match='cel_match_value', + message_bus='message_bus_value', + destination='destination_value', + ) + response = client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, enrollment.Enrollment) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.cel_match == 'cel_match_value' + assert response.message_bus == 'message_bus_value' + assert response.destination == 'destination_value' + + +def test_get_enrollment_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 = EventarcClient( + 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 = eventarc.GetEnrollmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetEnrollmentRequest( + name='name_value', + ) + +def test_get_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + request = {} + client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_enrollment(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_enrollment_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 = EventarcAsyncClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + await client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetEnrollmentRequest): + client = EventarcAsyncClient( + 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_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + cel_match='cel_match_value', + message_bus='message_bus_value', + destination='destination_value', + )) + response = await client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, enrollment.Enrollment) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.cel_match == 'cel_match_value' + assert response.message_bus == 'message_bus_value' + assert response.destination == 'destination_value' + + +@pytest.mark.asyncio +async def test_get_enrollment_async_from_dict(): + await test_get_enrollment_async(request_type=dict) + +def test_get_enrollment_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetEnrollmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + call.return_value = enrollment.Enrollment() + client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_enrollment_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetEnrollmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment()) + await client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_enrollment_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = enrollment.Enrollment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_enrollment( + name='name_value', + ) + + # 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_enrollment_flattened_error(): + client = EventarcClient( + credentials=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_enrollment( + eventarc.GetEnrollmentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = enrollment.Enrollment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_enrollment( + name='name_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_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + 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_enrollment( + eventarc.GetEnrollmentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListEnrollmentsRequest, + dict, +]) +def test_list_enrollments(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListEnrollmentsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListEnrollmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnrollmentsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_enrollments_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 = EventarcClient( + 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 = eventarc.ListEnrollmentsRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_enrollments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListEnrollmentsRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + +def test_list_enrollments_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 = EventarcClient( + 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_enrollments 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_enrollments] = mock_rpc + request = {} + client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_enrollments(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_enrollments_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 = EventarcAsyncClient( + 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_enrollments 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_enrollments] = mock_rpc + + request = {} + await client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_enrollments(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_enrollments_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListEnrollmentsRequest): + client = EventarcAsyncClient( + 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_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListEnrollmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnrollmentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_enrollments_async_from_dict(): + await test_list_enrollments_async(request_type=dict) + +def test_list_enrollments_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListEnrollmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + call.return_value = eventarc.ListEnrollmentsResponse() + client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_enrollments_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListEnrollmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse()) + await client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_enrollments_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListEnrollmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_enrollments( + 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_enrollments_flattened_error(): + client = EventarcClient( + credentials=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_enrollments( + eventarc.ListEnrollmentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_enrollments_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListEnrollmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_enrollments( + 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_enrollments_flattened_error_async(): + client = EventarcAsyncClient( + 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_enrollments( + eventarc.ListEnrollmentsRequest(), + parent='parent_value', + ) + + +def test_list_enrollments_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_enrollments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token='abc', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token='ghi', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_enrollments(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, enrollment.Enrollment) + for i in results) +def test_list_enrollments_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_enrollments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token='abc', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token='ghi', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_enrollments(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_enrollments_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token='abc', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token='ghi', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_enrollments(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, enrollment.Enrollment) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_enrollments_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token='abc', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token='ghi', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + 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_enrollments(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", [ + eventarc.CreateEnrollmentRequest, + dict, +]) +def test_create_enrollment(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_enrollment_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 = EventarcClient( + 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 = eventarc.CreateEnrollmentRequest( + parent='parent_value', + enrollment_id='enrollment_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateEnrollmentRequest( + parent='parent_value', + enrollment_id='enrollment_id_value', + ) + +def test_create_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + request = {} + client.create_enrollment(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_enrollment(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_enrollment_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 = EventarcAsyncClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + await client.create_enrollment(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_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateEnrollmentRequest): + client = EventarcAsyncClient( + 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_enrollment), + '__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_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateEnrollmentRequest() + 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_enrollment_async_from_dict(): + await test_create_enrollment_async(request_type=dict) + +def test_create_enrollment_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateEnrollmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_enrollment_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreateEnrollmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_enrollment_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__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_enrollment( + parent='parent_value', + enrollment=gce_enrollment.Enrollment(name='name_value'), + enrollment_id='enrollment_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].enrollment + mock_val = gce_enrollment.Enrollment(name='name_value') + assert arg == mock_val + arg = args[0].enrollment_id + mock_val = 'enrollment_id_value' + assert arg == mock_val + + +def test_create_enrollment_flattened_error(): + client = EventarcClient( + credentials=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_enrollment( + eventarc.CreateEnrollmentRequest(), + parent='parent_value', + enrollment=gce_enrollment.Enrollment(name='name_value'), + enrollment_id='enrollment_id_value', + ) + +@pytest.mark.asyncio +async def test_create_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__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_enrollment( + parent='parent_value', + enrollment=gce_enrollment.Enrollment(name='name_value'), + enrollment_id='enrollment_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].enrollment + mock_val = gce_enrollment.Enrollment(name='name_value') + assert arg == mock_val + arg = args[0].enrollment_id + mock_val = 'enrollment_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + 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_enrollment( + eventarc.CreateEnrollmentRequest(), + parent='parent_value', + enrollment=gce_enrollment.Enrollment(name='name_value'), + enrollment_id='enrollment_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateEnrollmentRequest, + dict, +]) +def test_update_enrollment(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_enrollment_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 = EventarcClient( + 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 = eventarc.UpdateEnrollmentRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateEnrollmentRequest( + ) + +def test_update_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + request = {} + client.update_enrollment(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.update_enrollment(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_enrollment_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 = EventarcAsyncClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + await client.update_enrollment(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.update_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateEnrollmentRequest): + client = EventarcAsyncClient( + 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_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateEnrollmentRequest() + 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_update_enrollment_async_from_dict(): + await test_update_enrollment_async(request_type=dict) + +def test_update_enrollment_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateEnrollmentRequest() + + request.enrollment.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'enrollment.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_enrollment_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdateEnrollmentRequest() + + request.enrollment.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'enrollment.name=name_value', + ) in kw['metadata'] + + +def test_update_enrollment_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_enrollment( + enrollment=gce_enrollment.Enrollment(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].enrollment + mock_val = gce_enrollment.Enrollment(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_enrollment_flattened_error(): + client = EventarcClient( + credentials=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_enrollment( + eventarc.UpdateEnrollmentRequest(), + enrollment=gce_enrollment.Enrollment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_enrollment( + enrollment=gce_enrollment.Enrollment(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].enrollment + mock_val = gce_enrollment.Enrollment(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_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + 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_enrollment( + eventarc.UpdateEnrollmentRequest(), + enrollment=gce_enrollment.Enrollment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteEnrollmentRequest, + dict, +]) +def test_delete_enrollment(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_enrollment_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 = EventarcClient( + 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 = eventarc.DeleteEnrollmentRequest( + 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_enrollment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteEnrollmentRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + request = {} + client.delete_enrollment(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_enrollment(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_enrollment_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 = EventarcAsyncClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + await client.delete_enrollment(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_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteEnrollmentRequest): + client = EventarcAsyncClient( + 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_enrollment), + '__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_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteEnrollmentRequest() + 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_enrollment_async_from_dict(): + await test_delete_enrollment_async(request_type=dict) + +def test_delete_enrollment_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteEnrollmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_enrollment_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeleteEnrollmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_enrollment_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__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_enrollment( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + + +def test_delete_enrollment_flattened_error(): + client = EventarcClient( + credentials=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_enrollment( + eventarc.DeleteEnrollmentRequest(), + name='name_value', + etag='etag_value', + ) + +@pytest.mark.asyncio +async def test_delete_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__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_enrollment( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + 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_enrollment( + eventarc.DeleteEnrollmentRequest(), + name='name_value', + etag='etag_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetPipelineRequest, + dict, +]) +def test_get_pipeline(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pipeline.Pipeline( + name='name_value', + uid='uid_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + etag='etag_value', + ) + response = client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetPipelineRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pipeline.Pipeline) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.display_name == 'display_name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.etag == 'etag_value' + + +def test_get_pipeline_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 = EventarcClient( + 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 = eventarc.GetPipelineRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_pipeline(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetPipelineRequest( + name='name_value', + ) + +def test_get_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + request = {} + client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_pipeline(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_pipeline_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 = EventarcAsyncClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + await client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetPipelineRequest): + client = EventarcAsyncClient( + 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_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline( + name='name_value', + uid='uid_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + etag='etag_value', + )) + response = await client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetPipelineRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pipeline.Pipeline) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.display_name == 'display_name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_pipeline_async_from_dict(): + await test_get_pipeline_async(request_type=dict) + +def test_get_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetPipelineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + call.return_value = pipeline.Pipeline() + client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_pipeline_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetPipelineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline()) + await client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pipeline.Pipeline() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_pipeline( + name='name_value', + ) + + # 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_pipeline_flattened_error(): + client = EventarcClient( + credentials=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_pipeline( + eventarc.GetPipelineRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_pipeline_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pipeline.Pipeline() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_pipeline( + name='name_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_pipeline_flattened_error_async(): + client = EventarcAsyncClient( + 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_pipeline( + eventarc.GetPipelineRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListPipelinesRequest, + dict, +]) +def test_list_pipelines(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListPipelinesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListPipelinesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPipelinesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_pipelines_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 = EventarcClient( + 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 = eventarc.ListPipelinesRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_pipelines(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListPipelinesRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + +def test_list_pipelines_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 = EventarcClient( + 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_pipelines 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_pipelines] = mock_rpc + request = {} + client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_pipelines(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_pipelines_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 = EventarcAsyncClient( + 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_pipelines 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_pipelines] = mock_rpc + + request = {} + await client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_pipelines(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_pipelines_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListPipelinesRequest): + client = EventarcAsyncClient( + 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_pipelines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListPipelinesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPipelinesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_pipelines_async_from_dict(): + await test_list_pipelines_async(request_type=dict) + +def test_list_pipelines_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListPipelinesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + call.return_value = eventarc.ListPipelinesResponse() + client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_pipelines_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListPipelinesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse()) + await client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_pipelines_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListPipelinesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_pipelines( + 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_pipelines_flattened_error(): + client = EventarcClient( + credentials=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_pipelines( + eventarc.ListPipelinesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_pipelines_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListPipelinesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_pipelines( + 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_pipelines_flattened_error_async(): + client = EventarcAsyncClient( + 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_pipelines( + eventarc.ListPipelinesRequest(), + parent='parent_value', + ) + + +def test_list_pipelines_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_pipelines), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token='abc', + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token='def', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token='ghi', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_pipelines(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, pipeline.Pipeline) + for i in results) +def test_list_pipelines_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_pipelines), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token='abc', + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token='def', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token='ghi', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) + pages = list(client.list_pipelines(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_pipelines_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token='abc', + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token='def', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token='ghi', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_pipelines(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, pipeline.Pipeline) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_pipelines_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token='abc', + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token='def', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token='ghi', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + 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_pipelines(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", [ + eventarc.CreatePipelineRequest, + dict, +]) +def test_create_pipeline(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreatePipelineRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_pipeline_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 = EventarcClient( + 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 = eventarc.CreatePipelineRequest( + parent='parent_value', + pipeline_id='pipeline_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_pipeline(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreatePipelineRequest( + parent='parent_value', + pipeline_id='pipeline_id_value', + ) + +def test_create_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + request = {} + client.create_pipeline(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_pipeline(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_pipeline_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 = EventarcAsyncClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + await client.create_pipeline(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_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreatePipelineRequest): + client = EventarcAsyncClient( + 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_pipeline), + '__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_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreatePipelineRequest() + 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_pipeline_async_from_dict(): + await test_create_pipeline_async(request_type=dict) + +def test_create_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreatePipelineRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_pipeline_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreatePipelineRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__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_pipeline( + parent='parent_value', + pipeline=gce_pipeline.Pipeline(name='name_value'), + pipeline_id='pipeline_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].pipeline + mock_val = gce_pipeline.Pipeline(name='name_value') + assert arg == mock_val + arg = args[0].pipeline_id + mock_val = 'pipeline_id_value' + assert arg == mock_val + + +def test_create_pipeline_flattened_error(): + client = EventarcClient( + credentials=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_pipeline( + eventarc.CreatePipelineRequest(), + parent='parent_value', + pipeline=gce_pipeline.Pipeline(name='name_value'), + pipeline_id='pipeline_id_value', + ) + +@pytest.mark.asyncio +async def test_create_pipeline_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__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_pipeline( + parent='parent_value', + pipeline=gce_pipeline.Pipeline(name='name_value'), + pipeline_id='pipeline_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].pipeline + mock_val = gce_pipeline.Pipeline(name='name_value') + assert arg == mock_val + arg = args[0].pipeline_id + mock_val = 'pipeline_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_pipeline_flattened_error_async(): + client = EventarcAsyncClient( + 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_pipeline( + eventarc.CreatePipelineRequest(), + parent='parent_value', + pipeline=gce_pipeline.Pipeline(name='name_value'), + pipeline_id='pipeline_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdatePipelineRequest, + dict, +]) +def test_update_pipeline(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdatePipelineRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_pipeline_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 = EventarcClient( + 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 = eventarc.UpdatePipelineRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_pipeline(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdatePipelineRequest( + ) + +def test_update_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + request = {} + client.update_pipeline(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.update_pipeline(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_pipeline_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 = EventarcAsyncClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + await client.update_pipeline(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.update_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdatePipelineRequest): + client = EventarcAsyncClient( + 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_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdatePipelineRequest() + 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_update_pipeline_async_from_dict(): + await test_update_pipeline_async(request_type=dict) + +def test_update_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdatePipelineRequest() + + request.pipeline.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'pipeline.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_pipeline_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdatePipelineRequest() + + request.pipeline.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'pipeline.name=name_value', + ) in kw['metadata'] + + +def test_update_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_pipeline( + pipeline=gce_pipeline.Pipeline(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].pipeline + mock_val = gce_pipeline.Pipeline(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_pipeline_flattened_error(): + client = EventarcClient( + credentials=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_pipeline( + eventarc.UpdatePipelineRequest(), + pipeline=gce_pipeline.Pipeline(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_pipeline_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_pipeline( + pipeline=gce_pipeline.Pipeline(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].pipeline + mock_val = gce_pipeline.Pipeline(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_pipeline_flattened_error_async(): + client = EventarcAsyncClient( + 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_pipeline( + eventarc.UpdatePipelineRequest(), + pipeline=gce_pipeline.Pipeline(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeletePipelineRequest, + dict, +]) +def test_delete_pipeline(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeletePipelineRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_pipeline_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 = EventarcClient( + 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 = eventarc.DeletePipelineRequest( + 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_pipeline), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_pipeline(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeletePipelineRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + request = {} + client.delete_pipeline(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_pipeline(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_pipeline_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 = EventarcAsyncClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + await client.delete_pipeline(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_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeletePipelineRequest): + client = EventarcAsyncClient( + 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_pipeline), + '__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_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeletePipelineRequest() + 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_pipeline_async_from_dict(): + await test_delete_pipeline_async(request_type=dict) + +def test_delete_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeletePipelineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_pipeline_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeletePipelineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__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_pipeline( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + + +def test_delete_pipeline_flattened_error(): + client = EventarcClient( + credentials=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_pipeline( + eventarc.DeletePipelineRequest(), + name='name_value', + etag='etag_value', + ) + +@pytest.mark.asyncio +async def test_delete_pipeline_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__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_pipeline( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_pipeline_flattened_error_async(): + client = EventarcAsyncClient( + 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_pipeline( + eventarc.DeletePipelineRequest(), + name='name_value', + etag='etag_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetGoogleApiSourceRequest, + dict, +]) +def test_get_google_api_source(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = google_api_source.GoogleApiSource( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + destination='destination_value', + crypto_key_name='crypto_key_name_value', + ) + response = client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, google_api_source.GoogleApiSource) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.destination == 'destination_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +def test_get_google_api_source_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 = EventarcClient( + 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 = eventarc.GetGoogleApiSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetGoogleApiSourceRequest( + name='name_value', + ) + +def test_get_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + request = {} + client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_api_source(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_google_api_source_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 = EventarcAsyncClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + await client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetGoogleApiSourceRequest): + client = EventarcAsyncClient( + 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_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + destination='destination_value', + crypto_key_name='crypto_key_name_value', + )) + response = await client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, google_api_source.GoogleApiSource) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.destination == 'destination_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.asyncio +async def test_get_google_api_source_async_from_dict(): + await test_get_google_api_source_async(request_type=dict) + +def test_get_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetGoogleApiSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + call.return_value = google_api_source.GoogleApiSource() + client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.GetGoogleApiSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource()) + await client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = google_api_source.GoogleApiSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_google_api_source( + name='name_value', + ) + + # 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_google_api_source_flattened_error(): + client = EventarcClient( + credentials=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_google_api_source( + eventarc.GetGoogleApiSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = google_api_source.GoogleApiSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_google_api_source( + name='name_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_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_api_source( + eventarc.GetGoogleApiSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListGoogleApiSourcesRequest, + dict, +]) +def test_list_google_api_sources(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListGoogleApiSourcesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListGoogleApiSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleApiSourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_google_api_sources_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 = EventarcClient( + 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 = eventarc.ListGoogleApiSourcesRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_google_api_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListGoogleApiSourcesRequest( + parent='parent_value', + page_token='page_token_value', + order_by='order_by_value', + filter='filter_value', + ) + +def test_list_google_api_sources_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 = EventarcClient( + 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_google_api_sources 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_google_api_sources] = mock_rpc + request = {} + client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_api_sources(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_google_api_sources_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 = EventarcAsyncClient( + 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_google_api_sources 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_google_api_sources] = mock_rpc + + request = {} + await client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_google_api_sources(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_google_api_sources_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListGoogleApiSourcesRequest): + client = EventarcAsyncClient( + 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_google_api_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListGoogleApiSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleApiSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async_from_dict(): + await test_list_google_api_sources_async(request_type=dict) + +def test_list_google_api_sources_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListGoogleApiSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + call.return_value = eventarc.ListGoogleApiSourcesResponse() + client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_google_api_sources_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.ListGoogleApiSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse()) + await client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_google_api_sources_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListGoogleApiSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_google_api_sources( + 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_google_api_sources_flattened_error(): + client = EventarcClient( + credentials=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_google_api_sources( + eventarc.ListGoogleApiSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_google_api_sources_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListGoogleApiSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_google_api_sources( + 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_google_api_sources_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_api_sources( + eventarc.ListGoogleApiSourcesRequest(), + parent='parent_value', + ) + + +def test_list_google_api_sources_pager(transport_name: str = "grpc"): + client = EventarcClient( + 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_google_api_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token='abc', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token='def', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token='ghi', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_google_api_sources(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, google_api_source.GoogleApiSource) + for i in results) +def test_list_google_api_sources_pages(transport_name: str = "grpc"): + client = EventarcClient( + 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_google_api_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token='abc', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token='def', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token='ghi', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_google_api_sources(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_google_api_sources_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token='abc', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token='def', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token='ghi', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_google_api_sources(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, google_api_source.GoogleApiSource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token='abc', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token='def', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token='ghi', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + 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_google_api_sources(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", [ + eventarc.CreateGoogleApiSourceRequest, + dict, +]) +def test_create_google_api_source(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_google_api_source_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 = EventarcClient( + 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 = eventarc.CreateGoogleApiSourceRequest( + parent='parent_value', + google_api_source_id='google_api_source_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateGoogleApiSourceRequest( + parent='parent_value', + google_api_source_id='google_api_source_id_value', + ) + +def test_create_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + request = {} + client.create_google_api_source(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_google_api_source(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_google_api_source_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 = EventarcAsyncClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + await client.create_google_api_source(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_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateGoogleApiSourceRequest): + client = EventarcAsyncClient( + 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_google_api_source), + '__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_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateGoogleApiSourceRequest() + 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_google_api_source_async_from_dict(): + await test_create_google_api_source_async(request_type=dict) + +def test_create_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateGoogleApiSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.CreateGoogleApiSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__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_google_api_source( + parent='parent_value', + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + google_api_source_id='google_api_source_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].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(name='name_value') + assert arg == mock_val + arg = args[0].google_api_source_id + mock_val = 'google_api_source_id_value' + assert arg == mock_val + + +def test_create_google_api_source_flattened_error(): + client = EventarcClient( + credentials=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_google_api_source( + eventarc.CreateGoogleApiSourceRequest(), + parent='parent_value', + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + google_api_source_id='google_api_source_id_value', + ) + +@pytest.mark.asyncio +async def test_create_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__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_google_api_source( + parent='parent_value', + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + google_api_source_id='google_api_source_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].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(name='name_value') + assert arg == mock_val + arg = args[0].google_api_source_id + mock_val = 'google_api_source_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_api_source( + eventarc.CreateGoogleApiSourceRequest(), + parent='parent_value', + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + google_api_source_id='google_api_source_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateGoogleApiSourceRequest, + dict, +]) +def test_update_google_api_source(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_google_api_source_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 = EventarcClient( + 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 = eventarc.UpdateGoogleApiSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateGoogleApiSourceRequest( + ) + +def test_update_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + request = {} + client.update_google_api_source(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.update_google_api_source(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_google_api_source_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 = EventarcAsyncClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + await client.update_google_api_source(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.update_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateGoogleApiSourceRequest): + client = EventarcAsyncClient( + 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_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateGoogleApiSourceRequest() + 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_update_google_api_source_async_from_dict(): + await test_update_google_api_source_async(request_type=dict) + +def test_update_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateGoogleApiSourceRequest() + + request.google_api_source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_api_source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.UpdateGoogleApiSourceRequest() + + request.google_api_source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_api_source.name=name_value', + ) in kw['metadata'] + + +def test_update_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_google_api_source( + google_api_source=gce_google_api_source.GoogleApiSource(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].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(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_google_api_source_flattened_error(): + client = EventarcClient( + credentials=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_google_api_source( + eventarc.UpdateGoogleApiSourceRequest(), + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_google_api_source( + google_api_source=gce_google_api_source.GoogleApiSource(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].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(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_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_api_source( + eventarc.UpdateGoogleApiSourceRequest(), + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteGoogleApiSourceRequest, + dict, +]) +def test_delete_google_api_source(request_type, transport: str = 'grpc'): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_google_api_source_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 = EventarcClient( + 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 = eventarc.DeleteGoogleApiSourceRequest( + 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_google_api_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteGoogleApiSourceRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + request = {} + client.delete_google_api_source(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_google_api_source(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_google_api_source_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 = EventarcAsyncClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + await client.delete_google_api_source(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_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteGoogleApiSourceRequest): + client = EventarcAsyncClient( + 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_google_api_source), + '__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_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteGoogleApiSourceRequest() + 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_google_api_source_async_from_dict(): + await test_delete_google_api_source_async(request_type=dict) + +def test_delete_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteGoogleApiSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + 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 = eventarc.DeleteGoogleApiSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__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_google_api_source( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + + +def test_delete_google_api_source_flattened_error(): + client = EventarcClient( + credentials=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_google_api_source( + eventarc.DeleteGoogleApiSourceRequest(), + name='name_value', + etag='etag_value', + ) + +@pytest.mark.asyncio +async def test_delete_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__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_google_api_source( + name='name_value', + etag='etag_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].etag + mock_val = 'etag_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + 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_google_api_source( + eventarc.DeleteGoogleApiSourceRequest(), + name='name_value', + etag='etag_value', + ) + + +def test_get_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_trigger(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_trigger_rest_required_fields(request_type=eventarc.GetTriggerRequest): + transport_class = transports.EventarcRestTransport + + 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_trigger._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_trigger._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = trigger.Trigger() + # 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 = trigger.Trigger.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 + + response = client.get_trigger(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_trigger_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_trigger_rest_flattened(): + client = EventarcClient( + 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 = trigger.Trigger() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/triggers/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 = trigger.Trigger.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 + + client.get_trigger(**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/*/triggers/*}" % client.transport._host, args[1]) + + +def test_get_trigger_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_trigger( + eventarc.GetTriggerRequest(), + name='name_value', + ) + + +def test_list_triggers_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 = EventarcClient( + 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_triggers 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_triggers] = mock_rpc + + request = {} + client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_triggers(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_triggers_rest_required_fields(request_type=eventarc.ListTriggersRequest): + transport_class = transports.EventarcRestTransport + + 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_triggers._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_triggers._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", )) + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListTriggersResponse() + # 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 = eventarc.ListTriggersResponse.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 + + response = client.list_triggers(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_triggers_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_triggers._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_triggers_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListTriggersResponse() + + # 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 = eventarc.ListTriggersResponse.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 + + client.list_triggers(**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/*}/triggers" % client.transport._host, args[1]) + + +def test_list_triggers_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_triggers( + eventarc.ListTriggersRequest(), + parent='parent_value', + ) + + +def test_list_triggers_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + trigger.Trigger(), + ], + next_page_token='abc', + ), + eventarc.ListTriggersResponse( + triggers=[], + next_page_token='def', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + ], + next_page_token='ghi', + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListTriggersResponse.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_triggers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, trigger.Trigger) + for i in results) + + pages = list(client.list_triggers(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.create_trigger(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_trigger(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_trigger_rest_required_fields(request_type=eventarc.CreateTriggerRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["trigger_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 "triggerId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "triggerId" in jsonified_request + assert jsonified_request["triggerId"] == request_init["trigger_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["triggerId"] = 'trigger_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_trigger._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("trigger_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 "triggerId" in jsonified_request + assert jsonified_request["triggerId"] == 'trigger_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_trigger(request) + + expected_params = [ + ( + "triggerId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_trigger_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(("triggerId", "validateOnly", )) & set(("parent", "trigger", "triggerId", ))) + + +def test_create_trigger_rest_flattened(): + client = EventarcClient( + 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', + trigger=gce_trigger.Trigger(name='name_value'), + trigger_id='trigger_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 + + client.create_trigger(**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/*}/triggers" % client.transport._host, args[1]) + + +def test_create_trigger_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_trigger( + eventarc.CreateTriggerRequest(), + parent='parent_value', + trigger=gce_trigger.Trigger(name='name_value'), + trigger_id='trigger_id_value', + ) + + +def test_update_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.update_trigger(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.update_trigger(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_trigger_rest_flattened(): + client = EventarcClient( + 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 = {'trigger': {'name': 'projects/sample1/locations/sample2/triggers/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + trigger=gce_trigger.Trigger(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + allow_missing=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_trigger(**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/{trigger.name=projects/*/locations/*/triggers/*}" % client.transport._host, args[1]) + + +def test_update_trigger_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_trigger( + eventarc.UpdateTriggerRequest(), + trigger=gce_trigger.Trigger(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + allow_missing=True, + ) + + +def test_delete_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.delete_trigger(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_trigger(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_trigger_rest_required_fields(request_type=eventarc.DeleteTriggerRequest): + transport_class = transports.EventarcRestTransport + + 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_trigger._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_trigger._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_trigger(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_trigger_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_trigger_rest_flattened(): + client = EventarcClient( + 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/triggers/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + allow_missing=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_trigger(**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/*/triggers/*}" % client.transport._host, args[1]) + + +def test_delete_trigger_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_trigger( + eventarc.DeleteTriggerRequest(), + name='name_value', + allow_missing=True, + ) + + +def test_get_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + + request = {} + client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel(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_channel_rest_required_fields(request_type=eventarc.GetChannelRequest): + transport_class = transports.EventarcRestTransport + + 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_channel._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_channel._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = channel.Channel() + # 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 = channel.Channel.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 + + response = client.get_channel(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_channel_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_channel_rest_flattened(): + client = EventarcClient( + 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 = channel.Channel() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/channels/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 = channel.Channel.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 + + client.get_channel(**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/*/channels/*}" % client.transport._host, args[1]) + + +def test_get_channel_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel( + eventarc.GetChannelRequest(), + name='name_value', + ) + + +def test_list_channels_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 = EventarcClient( + 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_channels 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_channels] = mock_rpc + + request = {} + client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channels(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_channels_rest_required_fields(request_type=eventarc.ListChannelsRequest): + transport_class = transports.EventarcRestTransport + + 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_channels._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_channels._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("order_by", "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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListChannelsResponse() + # 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 = eventarc.ListChannelsResponse.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 + + response = client.list_channels(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_channels_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_channels._get_unset_required_fields({}) + assert set(unset_fields) == (set(("orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_channels_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListChannelsResponse() + + # 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 = eventarc.ListChannelsResponse.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 + + client.list_channels(**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/*}/channels" % client.transport._host, args[1]) + + +def test_list_channels_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channels( + eventarc.ListChannelsRequest(), + parent='parent_value', + ) + + +def test_list_channels_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + channel.Channel(), + ], + next_page_token='abc', + ), + eventarc.ListChannelsResponse( + channels=[], + next_page_token='def', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListChannelsResponse.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_channels(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel.Channel) + for i in results) + + pages = list(client.list_channels(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_channel_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 = EventarcClient( + 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_channel_ 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_channel_] = mock_rpc + + request = {} + client.create_channel(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_channel(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_channel_rest_required_fields(request_type=eventarc.CreateChannelRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["channel_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 "channelId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == request_init["channel_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["channelId"] = 'channel_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("channel_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 "channelId" in jsonified_request + assert jsonified_request["channelId"] == 'channel_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_channel(request) + + expected_params = [ + ( + "channelId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_channel_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_channel_._get_unset_required_fields({}) + assert set(unset_fields) == (set(("channelId", "validateOnly", )) & set(("parent", "channel", "channelId", ))) + + +def test_create_channel_rest_flattened(): + client = EventarcClient( + 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', + channel=gce_channel.Channel(name='name_value'), + channel_id='channel_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 + + client.create_channel(**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/*}/channels" % client.transport._host, args[1]) + + +def test_create_channel_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel( + eventarc.CreateChannelRequest(), + parent='parent_value', + channel=gce_channel.Channel(name='name_value'), + channel_id='channel_id_value', + ) + + +def test_update_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + + request = {} + client.update_channel(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.update_channel(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_channel_rest_flattened(): + client = EventarcClient( + 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 = {'channel': {'name': 'projects/sample1/locations/sample2/channels/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + channel=gce_channel.Channel(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_channel(**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/{channel.name=projects/*/locations/*/channels/*}" % client.transport._host, args[1]) + + +def test_update_channel_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel( + eventarc.UpdateChannelRequest(), + channel=gce_channel.Channel(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + + request = {} + client.delete_channel(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_channel(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_channel_rest_required_fields(request_type=eventarc.DeleteChannelRequest): + transport_class = transports.EventarcRestTransport + + 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_channel._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_channel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_channel(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_channel_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", )) & set(("name", ))) + + +def test_delete_channel_rest_flattened(): + client = EventarcClient( + 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/channels/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_channel(**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/*/channels/*}" % client.transport._host, args[1]) + + +def test_delete_channel_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel( + eventarc.DeleteChannelRequest(), + name='name_value', + ) + + +def test_get_provider_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 = EventarcClient( + 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_provider 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_provider] = mock_rpc + + request = {} + client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_provider(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_provider_rest_required_fields(request_type=eventarc.GetProviderRequest): + transport_class = transports.EventarcRestTransport + + 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_provider._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_provider._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = discovery.Provider() + # 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 = discovery.Provider.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 + + response = client.get_provider(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_provider_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_provider._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_provider_rest_flattened(): + client = EventarcClient( + 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 = discovery.Provider() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/providers/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 = discovery.Provider.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 + + client.get_provider(**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/*/providers/*}" % client.transport._host, args[1]) + + +def test_get_provider_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_provider( + eventarc.GetProviderRequest(), + name='name_value', + ) + + +def test_list_providers_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 = EventarcClient( + 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_providers 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_providers] = mock_rpc + + request = {} + client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_providers(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_providers_rest_required_fields(request_type=eventarc.ListProvidersRequest): + transport_class = transports.EventarcRestTransport + + 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_providers._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_providers._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", )) + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListProvidersResponse() + # 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 = eventarc.ListProvidersResponse.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 + + response = client.list_providers(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_providers_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_providers._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_providers_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListProvidersResponse() + + # 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 = eventarc.ListProvidersResponse.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 + + client.list_providers(**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/*}/providers" % client.transport._host, args[1]) + + +def test_list_providers_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_providers( + eventarc.ListProvidersRequest(), + parent='parent_value', + ) + + +def test_list_providers_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + discovery.Provider(), + ], + next_page_token='abc', + ), + eventarc.ListProvidersResponse( + providers=[], + next_page_token='def', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + ], + next_page_token='ghi', + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListProvidersResponse.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_providers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, discovery.Provider) + for i in results) + + pages = list(client.list_providers(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_channel_connection_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 = EventarcClient( + 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_channel_connection 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_channel_connection] = mock_rpc + + request = {} + client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel_connection(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_channel_connection_rest_required_fields(request_type=eventarc.GetChannelConnectionRequest): + transport_class = transports.EventarcRestTransport + + 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_channel_connection._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_channel_connection._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = channel_connection.ChannelConnection() + # 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 = channel_connection.ChannelConnection.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 + + response = client.get_channel_connection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_channel_connection_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_channel_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_channel_connection_rest_flattened(): + client = EventarcClient( + 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 = channel_connection.ChannelConnection() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/channelConnections/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 = channel_connection.ChannelConnection.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 + + client.get_channel_connection(**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/*/channelConnections/*}" % client.transport._host, args[1]) + + +def test_get_channel_connection_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel_connection( + eventarc.GetChannelConnectionRequest(), + name='name_value', + ) + + +def test_list_channel_connections_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 = EventarcClient( + 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_channel_connections 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_channel_connections] = mock_rpc + + request = {} + client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channel_connections(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_channel_connections_rest_required_fields(request_type=eventarc.ListChannelConnectionsRequest): + transport_class = transports.EventarcRestTransport + + 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_channel_connections._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_channel_connections._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListChannelConnectionsResponse() + # 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 = eventarc.ListChannelConnectionsResponse.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 + + response = client.list_channel_connections(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_channel_connections_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_channel_connections._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_channel_connections_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListChannelConnectionsResponse() + + # 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 = eventarc.ListChannelConnectionsResponse.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 + + client.list_channel_connections(**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/*}/channelConnections" % client.transport._host, args[1]) + + +def test_list_channel_connections_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel_connections( + eventarc.ListChannelConnectionsRequest(), + parent='parent_value', + ) + + +def test_list_channel_connections_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + next_page_token='abc', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[], + next_page_token='def', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + ], + next_page_token='ghi', + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListChannelConnectionsResponse.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_channel_connections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel_connection.ChannelConnection) + for i in results) + + pages = list(client.list_channel_connections(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_channel_connection_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 = EventarcClient( + 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_channel_connection 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_channel_connection] = mock_rpc + + request = {} + client.create_channel_connection(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_channel_connection(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_channel_connection_rest_required_fields(request_type=eventarc.CreateChannelConnectionRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["channel_connection_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 "channelConnectionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "channelConnectionId" in jsonified_request + assert jsonified_request["channelConnectionId"] == request_init["channel_connection_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["channelConnectionId"] = 'channel_connection_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_connection._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("channel_connection_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "channelConnectionId" in jsonified_request + assert jsonified_request["channelConnectionId"] == 'channel_connection_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_channel_connection(request) + + expected_params = [ + ( + "channelConnectionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_channel_connection_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_channel_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(("channelConnectionId", )) & set(("parent", "channelConnection", "channelConnectionId", ))) + + +def test_create_channel_connection_rest_flattened(): + client = EventarcClient( + 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', + channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), + channel_connection_id='channel_connection_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 + + client.create_channel_connection(**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/*}/channelConnections" % client.transport._host, args[1]) + + +def test_create_channel_connection_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel_connection( + eventarc.CreateChannelConnectionRequest(), + parent='parent_value', + channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), + channel_connection_id='channel_connection_id_value', + ) + + +def test_delete_channel_connection_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 = EventarcClient( + 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_channel_connection 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_channel_connection] = mock_rpc + + request = {} + client.delete_channel_connection(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_channel_connection(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_channel_connection_rest_required_fields(request_type=eventarc.DeleteChannelConnectionRequest): + transport_class = transports.EventarcRestTransport + + 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_channel_connection._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_channel_connection._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_channel_connection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_channel_connection_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_channel_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_channel_connection_rest_flattened(): + client = EventarcClient( + 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/channelConnections/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_channel_connection(**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/*/channelConnections/*}" % client.transport._host, args[1]) + + +def test_delete_channel_connection_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_channel_connection( + eventarc.DeleteChannelConnectionRequest(), + name='name_value', + ) + + +def test_get_google_channel_config_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 = EventarcClient( + 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_google_channel_config 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_google_channel_config] = mock_rpc + + request = {} + client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_channel_config(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_google_channel_config_rest_required_fields(request_type=eventarc.GetGoogleChannelConfigRequest): + transport_class = transports.EventarcRestTransport + + 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_google_channel_config._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_google_channel_config._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = google_channel_config.GoogleChannelConfig() + # 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 = google_channel_config.GoogleChannelConfig.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 + + response = client.get_google_channel_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_google_channel_config_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_google_channel_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_google_channel_config_rest_flattened(): + client = EventarcClient( + 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 = google_channel_config.GoogleChannelConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/googleChannelConfig'} + + # 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 = google_channel_config.GoogleChannelConfig.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 + + client.get_google_channel_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/googleChannelConfig}" % client.transport._host, args[1]) + + +def test_get_google_channel_config_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_channel_config( + eventarc.GetGoogleChannelConfigRequest(), + name='name_value', + ) + + +def test_update_google_channel_config_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 = EventarcClient( + 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_google_channel_config 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_google_channel_config] = mock_rpc + + request = {} + client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_channel_config(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_google_channel_config_rest_required_fields(request_type=eventarc.UpdateGoogleChannelConfigRequest): + transport_class = transports.EventarcRestTransport + + 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_google_channel_config._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_google_channel_config._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gce_google_channel_config.GoogleChannelConfig() + # 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 = gce_google_channel_config.GoogleChannelConfig.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 + + response = client.update_google_channel_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_google_channel_config_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_google_channel_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("googleChannelConfig", ))) + + +def test_update_google_channel_config_rest_flattened(): + client = EventarcClient( + 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 = gce_google_channel_config.GoogleChannelConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'google_channel_config': {'name': 'projects/sample1/locations/sample2/googleChannelConfig'}} + + # get truthy value for each flattened field + mock_args = dict( + google_channel_config=gce_google_channel_config.GoogleChannelConfig(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 = gce_google_channel_config.GoogleChannelConfig.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 + + client.update_google_channel_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}" % client.transport._host, args[1]) + + +def test_update_google_channel_config_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_channel_config( + eventarc.UpdateGoogleChannelConfigRequest(), + google_channel_config=gce_google_channel_config.GoogleChannelConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.GetMessageBusRequest): + transport_class = transports.EventarcRestTransport + + 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_message_bus._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_message_bus._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message_bus.MessageBus() + # 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 = message_bus.MessageBus.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 + + response = client.get_message_bus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_message_bus_rest_flattened(): + client = EventarcClient( + 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 = message_bus.MessageBus() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/messageBuses/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 = message_bus.MessageBus.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 + + client.get_message_bus(**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/*/messageBuses/*}" % client.transport._host, args[1]) + + +def test_get_message_bus_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_message_bus( + eventarc.GetMessageBusRequest(), + name='name_value', + ) + + +def test_list_message_buses_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 = EventarcClient( + 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_message_buses 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_message_buses] = mock_rpc + + request = {} + client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_message_buses(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_message_buses_rest_required_fields(request_type=eventarc.ListMessageBusesRequest): + transport_class = transports.EventarcRestTransport + + 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_message_buses._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_message_buses._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", )) + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListMessageBusesResponse() + # 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 = eventarc.ListMessageBusesResponse.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 + + response = client.list_message_buses(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_message_buses_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_message_buses._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_message_buses_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListMessageBusesResponse() + + # 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 = eventarc.ListMessageBusesResponse.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 + + client.list_message_buses(**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/*}/messageBuses" % client.transport._host, args[1]) + + +def test_list_message_buses_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_message_buses( + eventarc.ListMessageBusesRequest(), + parent='parent_value', + ) + + +def test_list_message_buses_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token='def', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListMessageBusesResponse.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_message_buses(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message_bus.MessageBus) + for i in results) + + pages = list(client.list_message_buses(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_message_bus_enrollments_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 = EventarcClient( + 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_message_bus_enrollments 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_message_bus_enrollments] = mock_rpc + + request = {} + client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_message_bus_enrollments(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_message_bus_enrollments_rest_required_fields(request_type=eventarc.ListMessageBusEnrollmentsRequest): + transport_class = transports.EventarcRestTransport + + 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_message_bus_enrollments._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_message_bus_enrollments._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListMessageBusEnrollmentsResponse() + # 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 = eventarc.ListMessageBusEnrollmentsResponse.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 + + response = client.list_message_bus_enrollments(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_message_bus_enrollments_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_message_bus_enrollments._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_message_bus_enrollments_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListMessageBusEnrollmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/messageBuses/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 = eventarc.ListMessageBusEnrollmentsResponse.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 + + client.list_message_bus_enrollments(**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/*/messageBuses/*}:listEnrollments" % client.transport._host, args[1]) + + +def test_list_message_bus_enrollments_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_message_bus_enrollments( + eventarc.ListMessageBusEnrollmentsRequest(), + parent='parent_value', + ) + + +def test_list_message_bus_enrollments_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token='ghi', + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListMessageBusEnrollmentsResponse.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/messageBuses/sample3'} + + pager = client.list_message_bus_enrollments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, str) + for i in results) + + pages = list(client.list_message_bus_enrollments(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + client.create_message_bus(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_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.CreateMessageBusRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["message_bus_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 "messageBusId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_message_bus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "messageBusId" in jsonified_request + assert jsonified_request["messageBusId"] == request_init["message_bus_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["messageBusId"] = 'message_bus_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_message_bus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("message_bus_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 "messageBusId" in jsonified_request + assert jsonified_request["messageBusId"] == 'message_bus_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_message_bus(request) + + expected_params = [ + ( + "messageBusId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == (set(("messageBusId", "validateOnly", )) & set(("parent", "messageBus", "messageBusId", ))) + + +def test_create_message_bus_rest_flattened(): + client = EventarcClient( + 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', + message_bus=gce_message_bus.MessageBus(name='name_value'), + message_bus_id='message_bus_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 + + client.create_message_bus(**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/*}/messageBuses" % client.transport._host, args[1]) + + +def test_create_message_bus_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_message_bus( + eventarc.CreateMessageBusRequest(), + parent='parent_value', + message_bus=gce_message_bus.MessageBus(name='name_value'), + message_bus_id='message_bus_id_value', + ) + + +def test_update_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + client.update_message_bus(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.update_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.UpdateMessageBusRequest): + transport_class = transports.EventarcRestTransport + + 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_message_bus._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_message_bus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_message_bus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("messageBus", ))) + + +def test_update_message_bus_rest_flattened(): + client = EventarcClient( + 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 = {'message_bus': {'name': 'projects/sample1/locations/sample2/messageBuses/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + message_bus=gce_message_bus.MessageBus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_message_bus(**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/{message_bus.name=projects/*/locations/*/messageBuses/*}" % client.transport._host, args[1]) + + +def test_update_message_bus_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_message_bus( + eventarc.UpdateMessageBusRequest(), + message_bus=gce_message_bus.MessageBus(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + client.delete_message_bus(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_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.DeleteMessageBusRequest): + transport_class = transports.EventarcRestTransport + + 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_message_bus._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_message_bus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_message_bus(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_message_bus_rest_flattened(): + client = EventarcClient( + 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/messageBuses/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + etag='etag_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_message_bus(**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/*/messageBuses/*}" % client.transport._host, args[1]) + + +def test_delete_message_bus_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_message_bus( + eventarc.DeleteMessageBusRequest(), + name='name_value', + etag='etag_value', + ) + + +def test_get_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.GetEnrollmentRequest): + transport_class = transports.EventarcRestTransport + + 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_enrollment._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_enrollment._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = enrollment.Enrollment() + # 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 = enrollment.Enrollment.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 + + response = client.get_enrollment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_enrollment_rest_flattened(): + client = EventarcClient( + 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 = enrollment.Enrollment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/enrollments/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 = enrollment.Enrollment.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 + + client.get_enrollment(**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/*/enrollments/*}" % client.transport._host, args[1]) + + +def test_get_enrollment_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_enrollment( + eventarc.GetEnrollmentRequest(), + name='name_value', + ) + + +def test_list_enrollments_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 = EventarcClient( + 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_enrollments 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_enrollments] = mock_rpc + + request = {} + client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_enrollments(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_enrollments_rest_required_fields(request_type=eventarc.ListEnrollmentsRequest): + transport_class = transports.EventarcRestTransport + + 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_enrollments._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_enrollments._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", )) + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListEnrollmentsResponse() + # 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 = eventarc.ListEnrollmentsResponse.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 + + response = client.list_enrollments(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_enrollments_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_enrollments._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_enrollments_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListEnrollmentsResponse() + + # 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 = eventarc.ListEnrollmentsResponse.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 + + client.list_enrollments(**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/*}/enrollments" % client.transport._host, args[1]) + + +def test_list_enrollments_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_enrollments( + eventarc.ListEnrollmentsRequest(), + parent='parent_value', + ) + + +def test_list_enrollments_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token='abc', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token='def', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token='ghi', + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListEnrollmentsResponse.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_enrollments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, enrollment.Enrollment) + for i in results) + + pages = list(client.list_enrollments(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + client.create_enrollment(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_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.CreateEnrollmentRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["enrollment_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 "enrollmentId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_enrollment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "enrollmentId" in jsonified_request + assert jsonified_request["enrollmentId"] == request_init["enrollment_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["enrollmentId"] = 'enrollment_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_enrollment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("enrollment_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 "enrollmentId" in jsonified_request + assert jsonified_request["enrollmentId"] == 'enrollment_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_enrollment(request) + + expected_params = [ + ( + "enrollmentId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("enrollmentId", "validateOnly", )) & set(("parent", "enrollment", "enrollmentId", ))) + + +def test_create_enrollment_rest_flattened(): + client = EventarcClient( + 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', + enrollment=gce_enrollment.Enrollment(name='name_value'), + enrollment_id='enrollment_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 + + client.create_enrollment(**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/*}/enrollments" % client.transport._host, args[1]) + + +def test_create_enrollment_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_enrollment( + eventarc.CreateEnrollmentRequest(), + parent='parent_value', + enrollment=gce_enrollment.Enrollment(name='name_value'), + enrollment_id='enrollment_id_value', + ) + + +def test_update_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + client.update_enrollment(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.update_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.UpdateEnrollmentRequest): + transport_class = transports.EventarcRestTransport + + 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_enrollment._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_enrollment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_enrollment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("enrollment", ))) + + +def test_update_enrollment_rest_flattened(): + client = EventarcClient( + 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 = {'enrollment': {'name': 'projects/sample1/locations/sample2/enrollments/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + enrollment=gce_enrollment.Enrollment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_enrollment(**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/{enrollment.name=projects/*/locations/*/enrollments/*}" % client.transport._host, args[1]) + + +def test_update_enrollment_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_enrollment( + eventarc.UpdateEnrollmentRequest(), + enrollment=gce_enrollment.Enrollment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + client.delete_enrollment(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_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.DeleteEnrollmentRequest): + transport_class = transports.EventarcRestTransport + + 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_enrollment._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_enrollment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_enrollment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_enrollment_rest_flattened(): + client = EventarcClient( + 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/enrollments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + etag='etag_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_enrollment(**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/*/enrollments/*}" % client.transport._host, args[1]) + + +def test_delete_enrollment_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_enrollment( + eventarc.DeleteEnrollmentRequest(), + name='name_value', + etag='etag_value', + ) + + +def test_get_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.GetPipelineRequest): + transport_class = transports.EventarcRestTransport + + 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_pipeline._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_pipeline._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = pipeline.Pipeline() + # 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 = pipeline.Pipeline.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 + + response = client.get_pipeline(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_pipeline_rest_flattened(): + client = EventarcClient( + 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 = pipeline.Pipeline() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/pipelines/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 = pipeline.Pipeline.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 + + client.get_pipeline(**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/*/pipelines/*}" % client.transport._host, args[1]) + + +def test_get_pipeline_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_pipeline( + eventarc.GetPipelineRequest(), + name='name_value', + ) + + +def test_list_pipelines_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 = EventarcClient( + 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_pipelines 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_pipelines] = mock_rpc + + request = {} + client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_pipelines(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_pipelines_rest_required_fields(request_type=eventarc.ListPipelinesRequest): + transport_class = transports.EventarcRestTransport + + 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_pipelines._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_pipelines._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", )) + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListPipelinesResponse() + # 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 = eventarc.ListPipelinesResponse.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 + + response = client.list_pipelines(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_pipelines_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_pipelines._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_pipelines_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListPipelinesResponse() + + # 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 = eventarc.ListPipelinesResponse.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 + + client.list_pipelines(**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/*}/pipelines" % client.transport._host, args[1]) + + +def test_list_pipelines_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_pipelines( + eventarc.ListPipelinesRequest(), + parent='parent_value', + ) + + +def test_list_pipelines_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token='abc', + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token='def', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token='ghi', + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListPipelinesResponse.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_pipelines(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, pipeline.Pipeline) + for i in results) + + pages = list(client.list_pipelines(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.create_pipeline(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_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.CreatePipelineRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["pipeline_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 "pipelineId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_pipeline._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "pipelineId" in jsonified_request + assert jsonified_request["pipelineId"] == request_init["pipeline_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["pipelineId"] = 'pipeline_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_pipeline._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("pipeline_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 "pipelineId" in jsonified_request + assert jsonified_request["pipelineId"] == 'pipeline_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_pipeline(request) + + expected_params = [ + ( + "pipelineId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pipelineId", "validateOnly", )) & set(("parent", "pipeline", "pipelineId", ))) + + +def test_create_pipeline_rest_flattened(): + client = EventarcClient( + 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', + pipeline=gce_pipeline.Pipeline(name='name_value'), + pipeline_id='pipeline_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 + + client.create_pipeline(**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/*}/pipelines" % client.transport._host, args[1]) + + +def test_create_pipeline_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_pipeline( + eventarc.CreatePipelineRequest(), + parent='parent_value', + pipeline=gce_pipeline.Pipeline(name='name_value'), + pipeline_id='pipeline_id_value', + ) + + +def test_update_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.update_pipeline(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.update_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.UpdatePipelineRequest): + transport_class = transports.EventarcRestTransport + + 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_pipeline._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_pipeline._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_pipeline(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("pipeline", ))) + + +def test_update_pipeline_rest_flattened(): + client = EventarcClient( + 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 = {'pipeline': {'name': 'projects/sample1/locations/sample2/pipelines/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + pipeline=gce_pipeline.Pipeline(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_pipeline(**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/{pipeline.name=projects/*/locations/*/pipelines/*}" % client.transport._host, args[1]) + + +def test_update_pipeline_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_pipeline( + eventarc.UpdatePipelineRequest(), + pipeline=gce_pipeline.Pipeline(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.delete_pipeline(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_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.DeletePipelineRequest): + transport_class = transports.EventarcRestTransport + + 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_pipeline._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_pipeline._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_pipeline(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_pipeline_rest_flattened(): + client = EventarcClient( + 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/pipelines/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + etag='etag_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_pipeline(**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/*/pipelines/*}" % client.transport._host, args[1]) + + +def test_delete_pipeline_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_pipeline( + eventarc.DeletePipelineRequest(), + name='name_value', + etag='etag_value', + ) + + +def test_get_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.GetGoogleApiSourceRequest): + transport_class = transports.EventarcRestTransport + + 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_google_api_source._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_google_api_source._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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = google_api_source.GoogleApiSource() + # 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 = google_api_source.GoogleApiSource.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 + + response = client.get_google_api_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_google_api_source_rest_flattened(): + client = EventarcClient( + 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 = google_api_source.GoogleApiSource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 = google_api_source.GoogleApiSource.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 + + client.get_google_api_source(**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/*/googleApiSources/*}" % client.transport._host, args[1]) + + +def test_get_google_api_source_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_api_source( + eventarc.GetGoogleApiSourceRequest(), + name='name_value', + ) + + +def test_list_google_api_sources_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 = EventarcClient( + 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_google_api_sources 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_google_api_sources] = mock_rpc + + request = {} + client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_api_sources(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_google_api_sources_rest_required_fields(request_type=eventarc.ListGoogleApiSourcesRequest): + transport_class = transports.EventarcRestTransport + + 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_google_api_sources._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_google_api_sources._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", )) + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListGoogleApiSourcesResponse() + # 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 = eventarc.ListGoogleApiSourcesResponse.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 + + response = client.list_google_api_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_google_api_sources_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_google_api_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_google_api_sources_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListGoogleApiSourcesResponse() + + # 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 = eventarc.ListGoogleApiSourcesResponse.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 + + client.list_google_api_sources(**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/*}/googleApiSources" % client.transport._host, args[1]) + + +def test_list_google_api_sources_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_api_sources( + eventarc.ListGoogleApiSourcesRequest(), + parent='parent_value', + ) + + +def test_list_google_api_sources_rest_pager(transport: str = 'rest'): + client = EventarcClient( + 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 = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token='abc', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token='def', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token='ghi', + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListGoogleApiSourcesResponse.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_google_api_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, google_api_source.GoogleApiSource) + for i in results) + + pages = list(client.list_google_api_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + client.create_google_api_source(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_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.CreateGoogleApiSourceRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["google_api_source_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 "googleApiSourceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_google_api_source._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "googleApiSourceId" in jsonified_request + assert jsonified_request["googleApiSourceId"] == request_init["google_api_source_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["googleApiSourceId"] = 'google_api_source_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_google_api_source._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("google_api_source_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 "googleApiSourceId" in jsonified_request + assert jsonified_request["googleApiSourceId"] == 'google_api_source_id_value' + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_google_api_source(request) + + expected_params = [ + ( + "googleApiSourceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("googleApiSourceId", "validateOnly", )) & set(("parent", "googleApiSource", "googleApiSourceId", ))) + + +def test_create_google_api_source_rest_flattened(): + client = EventarcClient( + 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', + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + google_api_source_id='google_api_source_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 + + client.create_google_api_source(**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/*}/googleApiSources" % client.transport._host, args[1]) + + +def test_create_google_api_source_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_api_source( + eventarc.CreateGoogleApiSourceRequest(), + parent='parent_value', + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + google_api_source_id='google_api_source_id_value', + ) + + +def test_update_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + client.update_google_api_source(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.update_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.UpdateGoogleApiSourceRequest): + transport_class = transports.EventarcRestTransport + + 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_google_api_source._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_google_api_source._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_google_api_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("googleApiSource", ))) + + +def test_update_google_api_source_rest_flattened(): + client = EventarcClient( + 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 = {'google_api_source': {'name': 'projects/sample1/locations/sample2/googleApiSources/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_google_api_source(**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/{google_api_source.name=projects/*/locations/*/googleApiSources/*}" % client.transport._host, args[1]) + + +def test_update_google_api_source_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_api_source( + eventarc.UpdateGoogleApiSourceRequest(), + google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_google_api_source_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 = EventarcClient( + 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_google_api_source 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_google_api_source] = mock_rpc + + request = {} + client.delete_google_api_source(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_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.DeleteGoogleApiSourceRequest): + transport_class = transports.EventarcRestTransport + + 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_google_api_source._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_google_api_source._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_google_api_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) + + +def test_delete_google_api_source_rest_flattened(): + client = EventarcClient( + 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/googleApiSources/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + etag='etag_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_google_api_source(**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/*/googleApiSources/*}" % client.transport._host, args[1]) + + +def test_delete_google_api_source_rest_flattened_error(transport: str = 'rest'): + client = EventarcClient( + 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_google_api_source( + eventarc.DeleteGoogleApiSourceRequest(), + name='name_value', + etag='etag_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EventarcClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EventarcClient( + 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 = EventarcClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EventarcClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EventarcClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EventarcGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EventarcGrpcTransport, + transports.EventarcGrpcAsyncIOTransport, + transports.EventarcRestTransport, +]) +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 = EventarcClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EventarcClient( + 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_get_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + call.return_value = trigger.Trigger() + client.get_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetTriggerRequest() + + 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_triggers_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + call.return_value = eventarc.ListTriggersResponse() + client.list_triggers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListTriggersRequest() + + 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_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateTriggerRequest() + + 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_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateTriggerRequest() + + 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_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteTriggerRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + call.return_value = channel.Channel() + client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelRequest() + + 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_channels_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + call.return_value = eventarc.ListChannelsResponse() + client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelsRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateChannelRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelRequest() + + 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_provider_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + call.return_value = discovery.Provider() + client.get_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetProviderRequest() + + 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_providers_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + call.return_value = eventarc.ListProvidersResponse() + client.list_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListProvidersRequest() + + 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_channel_connection_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + call.return_value = channel_connection.ChannelConnection() + client.get_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelConnectionRequest() + + 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_channel_connections_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + call.return_value = eventarc.ListChannelConnectionsResponse() + client.list_channel_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelConnectionsRequest() + + 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_channel_connection_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelConnectionRequest() + + 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_channel_connection_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelConnectionRequest() + + 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_google_channel_config_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + call.return_value = google_channel_config.GoogleChannelConfig() + client.get_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleChannelConfigRequest() + + 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_google_channel_config_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + call.return_value = gce_google_channel_config.GoogleChannelConfig() + client.update_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleChannelConfigRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + call.return_value = message_bus.MessageBus() + client.get_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetMessageBusRequest() + + 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_message_buses_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + call.return_value = eventarc.ListMessageBusesResponse() + client.list_message_buses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusesRequest() + + 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_message_bus_enrollments_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + client.list_message_bus_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusEnrollmentsRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateMessageBusRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateMessageBusRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteMessageBusRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + call.return_value = enrollment.Enrollment() + client.get_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetEnrollmentRequest() + + 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_enrollments_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + call.return_value = eventarc.ListEnrollmentsResponse() + client.list_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListEnrollmentsRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateEnrollmentRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateEnrollmentRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteEnrollmentRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + call.return_value = pipeline.Pipeline() + client.get_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetPipelineRequest() + + 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_pipelines_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + call.return_value = eventarc.ListPipelinesResponse() + client.list_pipelines(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListPipelinesRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreatePipelineRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdatePipelineRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeletePipelineRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + call.return_value = google_api_source.GoogleApiSource() + client.get_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleApiSourceRequest() + + 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_google_api_sources_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + call.return_value = eventarc.ListGoogleApiSourcesResponse() + client.list_google_api_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListGoogleApiSourcesRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteGoogleApiSourceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EventarcAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EventarcAsyncClient( + 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_get_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger( + name='name_value', + uid='uid_value', + service_account='service_account_value', + channel='channel_value', + event_data_content_type='event_data_content_type_value', + satisfies_pzs=True, + etag='etag_value', + )) + await client.get_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetTriggerRequest() + + 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_triggers_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_triggers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListTriggersRequest() + + 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_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__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_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateTriggerRequest() + + 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_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__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.update_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateTriggerRequest() + + 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_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__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_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteTriggerRequest() + + 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_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel( + name='name_value', + uid='uid_value', + provider='provider_value', + state=channel.Channel.State.PENDING, + activation_token='activation_token_value', + crypto_key_name='crypto_key_name_value', + satisfies_pzs=True, + )) + await client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelRequest() + + 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_channels_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelsRequest() + + 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_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__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_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelRequest() + + 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_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__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.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateChannelRequest() + + 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_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__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_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelRequest() + + 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_provider_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider( + name='name_value', + display_name='display_name_value', + )) + await client.get_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetProviderRequest() + + 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_providers_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListProvidersRequest() + + 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_channel_connection_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection( + name='name_value', + uid='uid_value', + channel='channel_value', + activation_token='activation_token_value', + )) + await client.get_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelConnectionRequest() + + 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_channel_connections_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_channel_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelConnectionsRequest() + + 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_channel_connection_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__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_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelConnectionRequest() + + 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_channel_connection_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__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_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelConnectionRequest() + + 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_google_channel_config_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_name_value', + )) + await client.get_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleChannelConfigRequest() + + 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_google_channel_config_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_name_value', + )) + await client.update_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleChannelConfigRequest() + + 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_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + )) + await client.get_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetMessageBusRequest() + + 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_message_buses_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_message_buses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusesRequest() + + 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_message_bus_enrollments_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse( + enrollments=['enrollments_value'], + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_message_bus_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusEnrollmentsRequest() + + 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_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__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_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateMessageBusRequest() + + 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_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__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.update_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateMessageBusRequest() + + 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_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__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_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteMessageBusRequest() + + 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_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + cel_match='cel_match_value', + message_bus='message_bus_value', + destination='destination_value', + )) + await client.get_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetEnrollmentRequest() + + 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_enrollments_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListEnrollmentsRequest() + + 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_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__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_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateEnrollmentRequest() + + 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_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__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.update_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateEnrollmentRequest() + + 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_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__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_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteEnrollmentRequest() + + 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_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline( + name='name_value', + uid='uid_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + etag='etag_value', + )) + await client.get_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetPipelineRequest() + + 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_pipelines_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_pipelines(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListPipelinesRequest() + + 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_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__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_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreatePipelineRequest() + + 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_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__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.update_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdatePipelineRequest() + + 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_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__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_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeletePipelineRequest() + + 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_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + destination='destination_value', + crypto_key_name='crypto_key_name_value', + )) + await client.get_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleApiSourceRequest() + + 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_google_api_sources_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_google_api_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListGoogleApiSourcesRequest() + + 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_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__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_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__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.update_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__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_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteGoogleApiSourceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EventarcClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_trigger_rest_bad_request(request_type=eventarc.GetTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 + client.get_trigger(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetTriggerRequest, + dict, +]) +def test_get_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 = trigger.Trigger( + name='name_value', + uid='uid_value', + service_account='service_account_value', + channel='channel_value', + event_data_content_type='event_data_content_type_value', + satisfies_pzs=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 = trigger.Trigger.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 + response = client.get_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, trigger.Trigger) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.service_account == 'service_account_value' + assert response.channel == 'channel_value' + assert response.event_data_content_type == 'event_data_content_type_value' + assert response.satisfies_pzs is True + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_trigger") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_trigger") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetTriggerRequest.pb(eventarc.GetTriggerRequest()) + 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 + return_value = trigger.Trigger.to_json(trigger.Trigger()) + req.return_value.content = return_value + + request = eventarc.GetTriggerRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = trigger.Trigger() + + client.get_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_triggers_rest_bad_request(request_type=eventarc.ListTriggersRequest): + client = EventarcClient( + 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 + client.list_triggers(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListTriggersRequest, + dict, +]) +def test_list_triggers_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListTriggersResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListTriggersResponse.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 + response = client.list_triggers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTriggersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_triggers_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_triggers") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_triggers") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListTriggersRequest.pb(eventarc.ListTriggersRequest()) + 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 + return_value = eventarc.ListTriggersResponse.to_json(eventarc.ListTriggersResponse()) + req.return_value.content = return_value + + request = eventarc.ListTriggersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListTriggersResponse() + + client.list_triggers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_trigger_rest_bad_request(request_type=eventarc.CreateTriggerRequest): + client = EventarcClient( + 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 + client.create_trigger(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreateTriggerRequest, + dict, +]) +def test_create_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["trigger"] = {'name': 'name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'event_filters': [{'attribute': 'attribute_value', 'value': 'value_value', 'operator': 'operator_value'}], 'service_account': 'service_account_value', 'destination': {'cloud_run': {'service': 'service_value', 'path': 'path_value', 'region': 'region_value'}, 'cloud_function': 'cloud_function_value', 'gke': {'cluster': 'cluster_value', 'location': 'location_value', 'namespace': 'namespace_value', 'service': 'service_value', 'path': 'path_value'}, 'workflow': 'workflow_value', 'http_endpoint': {'uri': 'uri_value'}, 'network_config': {'network_attachment': 'network_attachment_value'}}, 'transport': {'pubsub': {'topic': 'topic_value', 'subscription': 'subscription_value'}}, 'labels': {}, 'channel': 'channel_value', 'conditions': {}, 'event_data_content_type': 'event_data_content_type_value', 'satisfies_pzs': 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 = eventarc.CreateTriggerRequest.meta.fields["trigger"] + + 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["trigger"].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["trigger"][field])): + del request_init["trigger"][field][i][subfield] + else: + del request_init["trigger"][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 + response = client.create_trigger(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_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_trigger") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_trigger") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateTriggerRequest.pb(eventarc.CreateTriggerRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateTriggerRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_trigger_rest_bad_request(request_type=eventarc.UpdateTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'trigger': {'name': 'projects/sample1/locations/sample2/triggers/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 + client.update_trigger(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateTriggerRequest, + dict, +]) +def test_update_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'trigger': {'name': 'projects/sample1/locations/sample2/triggers/sample3'}} + request_init["trigger"] = {'name': 'projects/sample1/locations/sample2/triggers/sample3', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'event_filters': [{'attribute': 'attribute_value', 'value': 'value_value', 'operator': 'operator_value'}], 'service_account': 'service_account_value', 'destination': {'cloud_run': {'service': 'service_value', 'path': 'path_value', 'region': 'region_value'}, 'cloud_function': 'cloud_function_value', 'gke': {'cluster': 'cluster_value', 'location': 'location_value', 'namespace': 'namespace_value', 'service': 'service_value', 'path': 'path_value'}, 'workflow': 'workflow_value', 'http_endpoint': {'uri': 'uri_value'}, 'network_config': {'network_attachment': 'network_attachment_value'}}, 'transport': {'pubsub': {'topic': 'topic_value', 'subscription': 'subscription_value'}}, 'labels': {}, 'channel': 'channel_value', 'conditions': {}, 'event_data_content_type': 'event_data_content_type_value', 'satisfies_pzs': 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 = eventarc.UpdateTriggerRequest.meta.fields["trigger"] + + 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["trigger"].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["trigger"][field])): + del request_init["trigger"][field][i][subfield] + else: + del request_init["trigger"][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 + response = client.update_trigger(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_update_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_trigger") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_trigger") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateTriggerRequest.pb(eventarc.UpdateTriggerRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateTriggerRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_trigger_rest_bad_request(request_type=eventarc.DeleteTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 + client.delete_trigger(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteTriggerRequest, + dict, +]) +def test_delete_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 + response = client.delete_trigger(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_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_trigger") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_trigger") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteTriggerRequest.pb(eventarc.DeleteTriggerRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteTriggerRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_channel_rest_bad_request(request_type=eventarc.GetChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channels/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 + client.get_channel(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetChannelRequest, + dict, +]) +def test_get_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channels/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 = channel.Channel( + name='name_value', + uid='uid_value', + provider='provider_value', + state=channel.Channel.State.PENDING, + activation_token='activation_token_value', + crypto_key_name='crypto_key_name_value', + satisfies_pzs=True, + pubsub_topic='pubsub_topic_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 = channel.Channel.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 + response = client.get_channel(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, channel.Channel) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.provider == 'provider_value' + assert response.state == channel.Channel.State.PENDING + assert response.activation_token == 'activation_token_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.satisfies_pzs is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_channel") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_channel") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetChannelRequest.pb(eventarc.GetChannelRequest()) + 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 + return_value = channel.Channel.to_json(channel.Channel()) + req.return_value.content = return_value + + request = eventarc.GetChannelRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = channel.Channel() + + client.get_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_channels_rest_bad_request(request_type=eventarc.ListChannelsRequest): + client = EventarcClient( + 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 + client.list_channels(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListChannelsRequest, + dict, +]) +def test_list_channels_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListChannelsResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListChannelsResponse.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 + response = client.list_channels(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_channels_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_channels") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_channels") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListChannelsRequest.pb(eventarc.ListChannelsRequest()) + 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 + return_value = eventarc.ListChannelsResponse.to_json(eventarc.ListChannelsResponse()) + req.return_value.content = return_value + + request = eventarc.ListChannelsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListChannelsResponse() + + client.list_channels(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_channel_rest_bad_request(request_type=eventarc.CreateChannelRequest): + client = EventarcClient( + 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 + client.create_channel(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreateChannelRequest, + dict, +]) +def test_create_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["channel"] = {'name': 'name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'provider': 'provider_value', 'pubsub_topic': 'pubsub_topic_value', 'state': 1, 'activation_token': 'activation_token_value', 'crypto_key_name': 'crypto_key_name_value', 'satisfies_pzs': True} + # 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 = eventarc.CreateChannelRequest.meta.fields["channel"] + + 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["channel"].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["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][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 + response = client.create_channel(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_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_channel") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_channel") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateChannelRequest.pb(eventarc.CreateChannelRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateChannelRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_channel_rest_bad_request(request_type=eventarc.UpdateChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'channel': {'name': 'projects/sample1/locations/sample2/channels/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 + client.update_channel(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateChannelRequest, + dict, +]) +def test_update_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'channel': {'name': 'projects/sample1/locations/sample2/channels/sample3'}} + request_init["channel"] = {'name': 'projects/sample1/locations/sample2/channels/sample3', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'provider': 'provider_value', 'pubsub_topic': 'pubsub_topic_value', 'state': 1, 'activation_token': 'activation_token_value', 'crypto_key_name': 'crypto_key_name_value', 'satisfies_pzs': True} + # 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 = eventarc.UpdateChannelRequest.meta.fields["channel"] + + 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["channel"].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["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][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 + response = client.update_channel(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_update_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_channel") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_channel") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateChannelRequest.pb(eventarc.UpdateChannelRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateChannelRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_channel_rest_bad_request(request_type=eventarc.DeleteChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channels/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 + client.delete_channel(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteChannelRequest, + dict, +]) +def test_delete_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channels/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 + response = client.delete_channel(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_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_channel") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_channel") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteChannelRequest.pb(eventarc.DeleteChannelRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteChannelRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_provider_rest_bad_request(request_type=eventarc.GetProviderRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/providers/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 + client.get_provider(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetProviderRequest, + dict, +]) +def test_get_provider_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/providers/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 = discovery.Provider( + 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 = discovery.Provider.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 + response = client.get_provider(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, discovery.Provider) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_provider_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_provider") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_provider") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetProviderRequest.pb(eventarc.GetProviderRequest()) + 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 + return_value = discovery.Provider.to_json(discovery.Provider()) + req.return_value.content = return_value + + request = eventarc.GetProviderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = discovery.Provider() + + client.get_provider(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_providers_rest_bad_request(request_type=eventarc.ListProvidersRequest): + client = EventarcClient( + 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 + client.list_providers(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListProvidersRequest, + dict, +]) +def test_list_providers_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListProvidersResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListProvidersResponse.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 + response = client.list_providers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProvidersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_providers_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_providers") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_providers") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListProvidersRequest.pb(eventarc.ListProvidersRequest()) + 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 + return_value = eventarc.ListProvidersResponse.to_json(eventarc.ListProvidersResponse()) + req.return_value.content = return_value + + request = eventarc.ListProvidersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListProvidersResponse() + + client.list_providers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_channel_connection_rest_bad_request(request_type=eventarc.GetChannelConnectionRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 + client.get_channel_connection(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetChannelConnectionRequest, + dict, +]) +def test_get_channel_connection_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 = channel_connection.ChannelConnection( + name='name_value', + uid='uid_value', + channel='channel_value', + activation_token='activation_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 = channel_connection.ChannelConnection.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 + response = client.get_channel_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_connection.ChannelConnection) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.channel == 'channel_value' + assert response.activation_token == 'activation_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_channel_connection_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_channel_connection") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_channel_connection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetChannelConnectionRequest.pb(eventarc.GetChannelConnectionRequest()) + 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 + return_value = channel_connection.ChannelConnection.to_json(channel_connection.ChannelConnection()) + req.return_value.content = return_value + + request = eventarc.GetChannelConnectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = channel_connection.ChannelConnection() + + client.get_channel_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_channel_connections_rest_bad_request(request_type=eventarc.ListChannelConnectionsRequest): + client = EventarcClient( + 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 + client.list_channel_connections(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListChannelConnectionsRequest, + dict, +]) +def test_list_channel_connections_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListChannelConnectionsResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListChannelConnectionsResponse.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 + response = client.list_channel_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelConnectionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_channel_connections_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_channel_connections") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_channel_connections") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListChannelConnectionsRequest.pb(eventarc.ListChannelConnectionsRequest()) + 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 + return_value = eventarc.ListChannelConnectionsResponse.to_json(eventarc.ListChannelConnectionsResponse()) + req.return_value.content = return_value + + request = eventarc.ListChannelConnectionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListChannelConnectionsResponse() + + client.list_channel_connections(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_channel_connection_rest_bad_request(request_type=eventarc.CreateChannelConnectionRequest): + client = EventarcClient( + 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 + client.create_channel_connection(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreateChannelConnectionRequest, + dict, +]) +def test_create_channel_connection_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["channel_connection"] = {'name': 'name_value', 'uid': 'uid_value', 'channel': 'channel_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'activation_token': 'activation_token_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 = eventarc.CreateChannelConnectionRequest.meta.fields["channel_connection"] + + 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["channel_connection"].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["channel_connection"][field])): + del request_init["channel_connection"][field][i][subfield] + else: + del request_init["channel_connection"][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 + response = client.create_channel_connection(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_channel_connection_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_channel_connection") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_channel_connection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateChannelConnectionRequest.pb(eventarc.CreateChannelConnectionRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateChannelConnectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_channel_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_channel_connection_rest_bad_request(request_type=eventarc.DeleteChannelConnectionRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 + client.delete_channel_connection(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteChannelConnectionRequest, + dict, +]) +def test_delete_channel_connection_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 + response = client.delete_channel_connection(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_channel_connection_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_channel_connection") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_channel_connection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteChannelConnectionRequest.pb(eventarc.DeleteChannelConnectionRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteChannelConnectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_channel_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_google_channel_config_rest_bad_request(request_type=eventarc.GetGoogleChannelConfigRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/googleChannelConfig'} + 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 + client.get_google_channel_config(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetGoogleChannelConfigRequest, + dict, +]) +def test_get_google_channel_config_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/googleChannelConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_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 = google_channel_config.GoogleChannelConfig.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 + response = client.get_google_channel_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, google_channel_config.GoogleChannelConfig) + assert response.name == 'name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_google_channel_config_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_google_channel_config") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_google_channel_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetGoogleChannelConfigRequest.pb(eventarc.GetGoogleChannelConfigRequest()) + 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 + return_value = google_channel_config.GoogleChannelConfig.to_json(google_channel_config.GoogleChannelConfig()) + req.return_value.content = return_value + + request = eventarc.GetGoogleChannelConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = google_channel_config.GoogleChannelConfig() + + client.get_google_channel_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_google_channel_config_rest_bad_request(request_type=eventarc.UpdateGoogleChannelConfigRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'google_channel_config': {'name': 'projects/sample1/locations/sample2/googleChannelConfig'}} + 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 + client.update_google_channel_config(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateGoogleChannelConfigRequest, + dict, +]) +def test_update_google_channel_config_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'google_channel_config': {'name': 'projects/sample1/locations/sample2/googleChannelConfig'}} + request_init["google_channel_config"] = {'name': 'projects/sample1/locations/sample2/googleChannelConfig', 'update_time': {'seconds': 751, 'nanos': 543}, 'crypto_key_name': 'crypto_key_name_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 = eventarc.UpdateGoogleChannelConfigRequest.meta.fields["google_channel_config"] + + 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["google_channel_config"].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["google_channel_config"][field])): + del request_init["google_channel_config"][field][i][subfield] + else: + del request_init["google_channel_config"][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 = gce_google_channel_config.GoogleChannelConfig( + name='name_value', + crypto_key_name='crypto_key_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 = gce_google_channel_config.GoogleChannelConfig.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 + response = client.update_google_channel_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) + assert response.name == 'name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_google_channel_config_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_google_channel_config") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_google_channel_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateGoogleChannelConfigRequest.pb(eventarc.UpdateGoogleChannelConfigRequest()) + 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 + return_value = gce_google_channel_config.GoogleChannelConfig.to_json(gce_google_channel_config.GoogleChannelConfig()) + req.return_value.content = return_value + + request = eventarc.UpdateGoogleChannelConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gce_google_channel_config.GoogleChannelConfig() + + client.update_google_channel_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_message_bus_rest_bad_request(request_type=eventarc.GetMessageBusRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 + client.get_message_bus(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetMessageBusRequest, + dict, +]) +def test_get_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 = message_bus.MessageBus( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + crypto_key_name='crypto_key_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 = message_bus.MessageBus.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 + response = client.get_message_bus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, message_bus.MessageBus) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_message_bus") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_message_bus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetMessageBusRequest.pb(eventarc.GetMessageBusRequest()) + 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 + return_value = message_bus.MessageBus.to_json(message_bus.MessageBus()) + req.return_value.content = return_value + + request = eventarc.GetMessageBusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = message_bus.MessageBus() + + client.get_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_message_buses_rest_bad_request(request_type=eventarc.ListMessageBusesRequest): + client = EventarcClient( + 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 + client.list_message_buses(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListMessageBusesRequest, + dict, +]) +def test_list_message_buses_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListMessageBusesResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListMessageBusesResponse.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 + response = client.list_message_buses(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_message_buses_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_message_buses") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_message_buses") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListMessageBusesRequest.pb(eventarc.ListMessageBusesRequest()) + 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 + return_value = eventarc.ListMessageBusesResponse.to_json(eventarc.ListMessageBusesResponse()) + req.return_value.content = return_value + + request = eventarc.ListMessageBusesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListMessageBusesResponse() + + client.list_message_buses(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_message_bus_enrollments_rest_bad_request(request_type=eventarc.ListMessageBusEnrollmentsRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/messageBuses/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 + client.list_message_bus_enrollments(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListMessageBusEnrollmentsRequest, + dict, +]) +def test_list_message_bus_enrollments_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/messageBuses/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 = eventarc.ListMessageBusEnrollmentsResponse( + enrollments=['enrollments_value'], + next_page_token='next_page_token_value', + 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 = eventarc.ListMessageBusEnrollmentsResponse.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 + response = client.list_message_bus_enrollments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusEnrollmentsPager) + assert response.enrollments == ['enrollments_value'] + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_message_bus_enrollments_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_message_bus_enrollments") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_message_bus_enrollments") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListMessageBusEnrollmentsRequest.pb(eventarc.ListMessageBusEnrollmentsRequest()) + 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 + return_value = eventarc.ListMessageBusEnrollmentsResponse.to_json(eventarc.ListMessageBusEnrollmentsResponse()) + req.return_value.content = return_value + + request = eventarc.ListMessageBusEnrollmentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListMessageBusEnrollmentsResponse() + + client.list_message_bus_enrollments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_message_bus_rest_bad_request(request_type=eventarc.CreateMessageBusRequest): + client = EventarcClient( + 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 + client.create_message_bus(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreateMessageBusRequest, + dict, +]) +def test_create_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["message_bus"] = {'name': 'name_value', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.CreateMessageBusRequest.meta.fields["message_bus"] + + 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["message_bus"].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["message_bus"][field])): + del request_init["message_bus"][field][i][subfield] + else: + del request_init["message_bus"][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 + response = client.create_message_bus(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_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_message_bus") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_message_bus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateMessageBusRequest.pb(eventarc.CreateMessageBusRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateMessageBusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_message_bus_rest_bad_request(request_type=eventarc.UpdateMessageBusRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'message_bus': {'name': 'projects/sample1/locations/sample2/messageBuses/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 + client.update_message_bus(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateMessageBusRequest, + dict, +]) +def test_update_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'message_bus': {'name': 'projects/sample1/locations/sample2/messageBuses/sample3'}} + request_init["message_bus"] = {'name': 'projects/sample1/locations/sample2/messageBuses/sample3', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.UpdateMessageBusRequest.meta.fields["message_bus"] + + 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["message_bus"].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["message_bus"][field])): + del request_init["message_bus"][field][i][subfield] + else: + del request_init["message_bus"][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 + response = client.update_message_bus(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_update_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_message_bus") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_message_bus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateMessageBusRequest.pb(eventarc.UpdateMessageBusRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateMessageBusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_message_bus_rest_bad_request(request_type=eventarc.DeleteMessageBusRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 + client.delete_message_bus(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteMessageBusRequest, + dict, +]) +def test_delete_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 + response = client.delete_message_bus(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_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_message_bus") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_message_bus") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteMessageBusRequest.pb(eventarc.DeleteMessageBusRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteMessageBusRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_enrollment_rest_bad_request(request_type=eventarc.GetEnrollmentRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 + client.get_enrollment(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetEnrollmentRequest, + dict, +]) +def test_get_enrollment_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 = enrollment.Enrollment( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + cel_match='cel_match_value', + message_bus='message_bus_value', + destination='destination_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 = enrollment.Enrollment.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 + response = client.get_enrollment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, enrollment.Enrollment) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.cel_match == 'cel_match_value' + assert response.message_bus == 'message_bus_value' + assert response.destination == 'destination_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_enrollment_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_enrollment") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_enrollment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetEnrollmentRequest.pb(eventarc.GetEnrollmentRequest()) + 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 + return_value = enrollment.Enrollment.to_json(enrollment.Enrollment()) + req.return_value.content = return_value + + request = eventarc.GetEnrollmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = enrollment.Enrollment() + + client.get_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_enrollments_rest_bad_request(request_type=eventarc.ListEnrollmentsRequest): + client = EventarcClient( + 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 + client.list_enrollments(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListEnrollmentsRequest, + dict, +]) +def test_list_enrollments_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListEnrollmentsResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListEnrollmentsResponse.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 + response = client.list_enrollments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnrollmentsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_enrollments_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_enrollments") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_enrollments") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListEnrollmentsRequest.pb(eventarc.ListEnrollmentsRequest()) + 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 + return_value = eventarc.ListEnrollmentsResponse.to_json(eventarc.ListEnrollmentsResponse()) + req.return_value.content = return_value + + request = eventarc.ListEnrollmentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListEnrollmentsResponse() + + client.list_enrollments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_enrollment_rest_bad_request(request_type=eventarc.CreateEnrollmentRequest): + client = EventarcClient( + 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 + client.create_enrollment(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreateEnrollmentRequest, + dict, +]) +def test_create_enrollment_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["enrollment"] = {'name': 'name_value', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'cel_match': 'cel_match_value', 'message_bus': 'message_bus_value', 'destination': 'destination_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 = eventarc.CreateEnrollmentRequest.meta.fields["enrollment"] + + 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["enrollment"].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["enrollment"][field])): + del request_init["enrollment"][field][i][subfield] + else: + del request_init["enrollment"][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 + response = client.create_enrollment(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_enrollment_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_enrollment") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_enrollment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateEnrollmentRequest.pb(eventarc.CreateEnrollmentRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateEnrollmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_enrollment_rest_bad_request(request_type=eventarc.UpdateEnrollmentRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'enrollment': {'name': 'projects/sample1/locations/sample2/enrollments/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 + client.update_enrollment(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateEnrollmentRequest, + dict, +]) +def test_update_enrollment_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'enrollment': {'name': 'projects/sample1/locations/sample2/enrollments/sample3'}} + request_init["enrollment"] = {'name': 'projects/sample1/locations/sample2/enrollments/sample3', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'cel_match': 'cel_match_value', 'message_bus': 'message_bus_value', 'destination': 'destination_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 = eventarc.UpdateEnrollmentRequest.meta.fields["enrollment"] + + 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["enrollment"].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["enrollment"][field])): + del request_init["enrollment"][field][i][subfield] + else: + del request_init["enrollment"][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 + response = client.update_enrollment(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_update_enrollment_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_enrollment") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_enrollment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateEnrollmentRequest.pb(eventarc.UpdateEnrollmentRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateEnrollmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_enrollment_rest_bad_request(request_type=eventarc.DeleteEnrollmentRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 + client.delete_enrollment(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteEnrollmentRequest, + dict, +]) +def test_delete_enrollment_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 + response = client.delete_enrollment(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_enrollment_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_enrollment") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_enrollment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteEnrollmentRequest.pb(eventarc.DeleteEnrollmentRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteEnrollmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_pipeline_rest_bad_request(request_type=eventarc.GetPipelineRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 + client.get_pipeline(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetPipelineRequest, + dict, +]) +def test_get_pipeline_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 = pipeline.Pipeline( + name='name_value', + uid='uid_value', + display_name='display_name_value', + crypto_key_name='crypto_key_name_value', + 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 = pipeline.Pipeline.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 + response = client.get_pipeline(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pipeline.Pipeline) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.display_name == 'display_name_value' + assert response.crypto_key_name == 'crypto_key_name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_pipeline_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_pipeline") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_pipeline") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetPipelineRequest.pb(eventarc.GetPipelineRequest()) + 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 + return_value = pipeline.Pipeline.to_json(pipeline.Pipeline()) + req.return_value.content = return_value + + request = eventarc.GetPipelineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = pipeline.Pipeline() + + client.get_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_pipelines_rest_bad_request(request_type=eventarc.ListPipelinesRequest): + client = EventarcClient( + 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 + client.list_pipelines(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListPipelinesRequest, + dict, +]) +def test_list_pipelines_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListPipelinesResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListPipelinesResponse.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 + response = client.list_pipelines(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPipelinesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_pipelines_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_pipelines") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_pipelines") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListPipelinesRequest.pb(eventarc.ListPipelinesRequest()) + 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 + return_value = eventarc.ListPipelinesResponse.to_json(eventarc.ListPipelinesResponse()) + req.return_value.content = return_value + + request = eventarc.ListPipelinesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListPipelinesResponse() + + client.list_pipelines(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_pipeline_rest_bad_request(request_type=eventarc.CreatePipelineRequest): + client = EventarcClient( + 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 + client.create_pipeline(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreatePipelineRequest, + dict, +]) +def test_create_pipeline_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["pipeline"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'uid': 'uid_value', 'annotations': {}, 'display_name': 'display_name_value', 'destinations': [{'network_config': {'network_attachment': 'network_attachment_value'}, 'http_endpoint': {'uri': 'uri_value', 'message_binding_template': 'message_binding_template_value'}, 'workflow': 'workflow_value', 'message_bus': 'message_bus_value', 'topic': 'topic_value', 'authentication_config': {'google_oidc': {'service_account': 'service_account_value', 'audience': 'audience_value'}, 'oauth_token': {'service_account': 'service_account_value', 'scope': 'scope_value'}}, 'output_payload_format': {'protobuf': {'schema_definition': 'schema_definition_value'}, 'avro': {'schema_definition': 'schema_definition_value'}, 'json': {}}}], 'mediations': [{'transformation': {'transformation_template': 'transformation_template_value'}}], 'crypto_key_name': 'crypto_key_name_value', 'input_payload_format': {}, 'logging_config': {'log_severity': 1}, 'retry_policy': {'max_attempts': 1303, 'min_retry_delay': {'seconds': 751, 'nanos': 543}, 'max_retry_delay': {}}, '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 = eventarc.CreatePipelineRequest.meta.fields["pipeline"] + + 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["pipeline"].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["pipeline"][field])): + del request_init["pipeline"][field][i][subfield] + else: + del request_init["pipeline"][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 + response = client.create_pipeline(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_pipeline_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_pipeline") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_pipeline") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreatePipelineRequest.pb(eventarc.CreatePipelineRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreatePipelineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_pipeline_rest_bad_request(request_type=eventarc.UpdatePipelineRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'pipeline': {'name': 'projects/sample1/locations/sample2/pipelines/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 + client.update_pipeline(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdatePipelineRequest, + dict, +]) +def test_update_pipeline_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'pipeline': {'name': 'projects/sample1/locations/sample2/pipelines/sample3'}} + request_init["pipeline"] = {'name': 'projects/sample1/locations/sample2/pipelines/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'uid': 'uid_value', 'annotations': {}, 'display_name': 'display_name_value', 'destinations': [{'network_config': {'network_attachment': 'network_attachment_value'}, 'http_endpoint': {'uri': 'uri_value', 'message_binding_template': 'message_binding_template_value'}, 'workflow': 'workflow_value', 'message_bus': 'message_bus_value', 'topic': 'topic_value', 'authentication_config': {'google_oidc': {'service_account': 'service_account_value', 'audience': 'audience_value'}, 'oauth_token': {'service_account': 'service_account_value', 'scope': 'scope_value'}}, 'output_payload_format': {'protobuf': {'schema_definition': 'schema_definition_value'}, 'avro': {'schema_definition': 'schema_definition_value'}, 'json': {}}}], 'mediations': [{'transformation': {'transformation_template': 'transformation_template_value'}}], 'crypto_key_name': 'crypto_key_name_value', 'input_payload_format': {}, 'logging_config': {'log_severity': 1}, 'retry_policy': {'max_attempts': 1303, 'min_retry_delay': {'seconds': 751, 'nanos': 543}, 'max_retry_delay': {}}, '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 = eventarc.UpdatePipelineRequest.meta.fields["pipeline"] + + 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["pipeline"].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["pipeline"][field])): + del request_init["pipeline"][field][i][subfield] + else: + del request_init["pipeline"][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 + response = client.update_pipeline(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_update_pipeline_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_pipeline") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_pipeline") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdatePipelineRequest.pb(eventarc.UpdatePipelineRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdatePipelineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_pipeline_rest_bad_request(request_type=eventarc.DeletePipelineRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 + client.delete_pipeline(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeletePipelineRequest, + dict, +]) +def test_delete_pipeline_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 + response = client.delete_pipeline(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_pipeline_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_pipeline") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_pipeline") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeletePipelineRequest.pb(eventarc.DeletePipelineRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeletePipelineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_google_api_source_rest_bad_request(request_type=eventarc.GetGoogleApiSourceRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 + client.get_google_api_source(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.GetGoogleApiSourceRequest, + dict, +]) +def test_get_google_api_source_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 = google_api_source.GoogleApiSource( + name='name_value', + uid='uid_value', + etag='etag_value', + display_name='display_name_value', + destination='destination_value', + crypto_key_name='crypto_key_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 = google_api_source.GoogleApiSource.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 + response = client.get_google_api_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, google_api_source.GoogleApiSource) + assert response.name == 'name_value' + assert response.uid == 'uid_value' + assert response.etag == 'etag_value' + assert response.display_name == 'display_name_value' + assert response.destination == 'destination_value' + assert response.crypto_key_name == 'crypto_key_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_google_api_source_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_google_api_source") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_get_google_api_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetGoogleApiSourceRequest.pb(eventarc.GetGoogleApiSourceRequest()) + 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 + return_value = google_api_source.GoogleApiSource.to_json(google_api_source.GoogleApiSource()) + req.return_value.content = return_value + + request = eventarc.GetGoogleApiSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = google_api_source.GoogleApiSource() + + client.get_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_google_api_sources_rest_bad_request(request_type=eventarc.ListGoogleApiSourcesRequest): + client = EventarcClient( + 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 + client.list_google_api_sources(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.ListGoogleApiSourcesRequest, + dict, +]) +def test_list_google_api_sources_rest_call_success(request_type): + client = EventarcClient( + 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 = eventarc.ListGoogleApiSourcesResponse( + next_page_token='next_page_token_value', + 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 = eventarc.ListGoogleApiSourcesResponse.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 + response = client.list_google_api_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleApiSourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_google_api_sources_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_google_api_sources") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_list_google_api_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListGoogleApiSourcesRequest.pb(eventarc.ListGoogleApiSourcesRequest()) + 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 + return_value = eventarc.ListGoogleApiSourcesResponse.to_json(eventarc.ListGoogleApiSourcesResponse()) + req.return_value.content = return_value + + request = eventarc.ListGoogleApiSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListGoogleApiSourcesResponse() + + client.list_google_api_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_google_api_source_rest_bad_request(request_type=eventarc.CreateGoogleApiSourceRequest): + client = EventarcClient( + 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 + client.create_google_api_source(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.CreateGoogleApiSourceRequest, + dict, +]) +def test_create_google_api_source_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["google_api_source"] = {'name': 'name_value', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'destination': 'destination_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.CreateGoogleApiSourceRequest.meta.fields["google_api_source"] + + 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["google_api_source"].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["google_api_source"][field])): + del request_init["google_api_source"][field][i][subfield] + else: + del request_init["google_api_source"][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 + response = client.create_google_api_source(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_google_api_source_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_create_google_api_source") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_create_google_api_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateGoogleApiSourceRequest.pb(eventarc.CreateGoogleApiSourceRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateGoogleApiSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_google_api_source_rest_bad_request(request_type=eventarc.UpdateGoogleApiSourceRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'google_api_source': {'name': 'projects/sample1/locations/sample2/googleApiSources/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 + client.update_google_api_source(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.UpdateGoogleApiSourceRequest, + dict, +]) +def test_update_google_api_source_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'google_api_source': {'name': 'projects/sample1/locations/sample2/googleApiSources/sample3'}} + request_init["google_api_source"] = {'name': 'projects/sample1/locations/sample2/googleApiSources/sample3', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'destination': 'destination_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.UpdateGoogleApiSourceRequest.meta.fields["google_api_source"] + + 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["google_api_source"].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["google_api_source"][field])): + del request_init["google_api_source"][field][i][subfield] + else: + del request_init["google_api_source"][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 + response = client.update_google_api_source(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_update_google_api_source_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_google_api_source") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_update_google_api_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateGoogleApiSourceRequest.pb(eventarc.UpdateGoogleApiSourceRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateGoogleApiSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_google_api_source_rest_bad_request(request_type=eventarc.DeleteGoogleApiSourceRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 + client.delete_google_api_source(request) + + +@pytest.mark.parametrize("request_type", [ + eventarc.DeleteGoogleApiSourceRequest, + dict, +]) +def test_delete_google_api_source_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 + response = client.delete_google_api_source(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_google_api_source_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_delete_google_api_source") as post, \ + mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_google_api_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteGoogleApiSourceRequest.pb(eventarc.DeleteGoogleApiSourceRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteGoogleApiSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = EventarcClient( + 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 + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = EventarcClient( + 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 + + 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 = EventarcClient( + 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 + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = EventarcClient( + 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 + + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/triggers/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 + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/triggers/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 + + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/triggers/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 + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/triggers/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 + + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/triggers/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 + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/triggers/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 + + 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_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = EventarcClient( + 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 + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = EventarcClient( + 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 + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = EventarcClient( + 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 + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = EventarcClient( + 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 + + 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 = EventarcClient( + 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 + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = EventarcClient( + 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 + + 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 = EventarcClient( + 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 + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = EventarcClient( + 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 + + 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 = EventarcClient( + 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_get_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trigger), + '__call__') as call: + client.get_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetTriggerRequest() + + 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_triggers_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_triggers), + '__call__') as call: + client.list_triggers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListTriggersRequest() + + 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_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trigger), + '__call__') as call: + client.create_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateTriggerRequest() + + 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_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trigger), + '__call__') as call: + client.update_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateTriggerRequest() + + 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_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_trigger), + '__call__') as call: + client.delete_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteTriggerRequest() + + 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_channel_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel), + '__call__') as call: + client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelRequest() + + 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_channels_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channels), + '__call__') as call: + client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelsRequest() + + 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_channel_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_), + '__call__') as call: + client.create_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelRequest() + + 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_channel_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_channel), + '__call__') as call: + client.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateChannelRequest() + + 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_channel_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel), + '__call__') as call: + client.delete_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelRequest() + + 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_provider_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_provider), + '__call__') as call: + client.get_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetProviderRequest() + + 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_providers_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_providers), + '__call__') as call: + client.list_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListProvidersRequest() + + 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_channel_connection_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), + '__call__') as call: + client.get_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelConnectionRequest() + + 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_channel_connections_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), + '__call__') as call: + client.list_channel_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelConnectionsRequest() + + 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_channel_connection_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), + '__call__') as call: + client.create_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelConnectionRequest() + + 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_channel_connection_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), + '__call__') as call: + client.delete_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelConnectionRequest() + + 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_google_channel_config_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), + '__call__') as call: + client.get_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleChannelConfigRequest() + + 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_google_channel_config_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), + '__call__') as call: + client.update_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleChannelConfigRequest() + + 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_message_bus_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_message_bus), + '__call__') as call: + client.get_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetMessageBusRequest() + + 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_message_buses_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + '__call__') as call: + client.list_message_buses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusesRequest() + + 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_message_bus_enrollments_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + '__call__') as call: + client.list_message_bus_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusEnrollmentsRequest() + + 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_message_bus_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), + '__call__') as call: + client.create_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateMessageBusRequest() + + 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_message_bus_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), + '__call__') as call: + client.update_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateMessageBusRequest() + + 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_message_bus_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), + '__call__') as call: + client.delete_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteMessageBusRequest() + + 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_enrollment_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_enrollment), + '__call__') as call: + client.get_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetEnrollmentRequest() + + 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_enrollments_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), + '__call__') as call: + client.list_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListEnrollmentsRequest() + + 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_enrollment_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), + '__call__') as call: + client.create_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateEnrollmentRequest() + + 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_enrollment_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), + '__call__') as call: + client.update_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateEnrollmentRequest() + + 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_enrollment_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), + '__call__') as call: + client.delete_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteEnrollmentRequest() + + 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_pipeline_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_pipeline), + '__call__') as call: + client.get_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetPipelineRequest() + + 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_pipelines_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), + '__call__') as call: + client.list_pipelines(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListPipelinesRequest() + + 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_pipeline_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_pipeline), + '__call__') as call: + client.create_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreatePipelineRequest() + + 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_pipeline_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_pipeline), + '__call__') as call: + client.update_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdatePipelineRequest() + + 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_pipeline_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_pipeline), + '__call__') as call: + client.delete_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeletePipelineRequest() + + 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_google_api_source_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), + '__call__') as call: + client.get_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleApiSourceRequest() + + 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_google_api_sources_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + '__call__') as call: + client.list_google_api_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListGoogleApiSourcesRequest() + + 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_google_api_source_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), + '__call__') as call: + client.create_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), + '__call__') as call: + client.update_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), + '__call__') as call: + client.delete_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteGoogleApiSourceRequest() + + assert args[0] == request_msg + + +def test_eventarc_rest_lro_client(): + client = EventarcClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EventarcGrpcTransport, + ) + +def test_eventarc_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EventarcTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_eventarc_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.eventarc_v1.services.eventarc.transports.EventarcTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EventarcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_trigger', + 'list_triggers', + 'create_trigger', + 'update_trigger', + 'delete_trigger', + 'get_channel', + 'list_channels', + 'create_channel_', + 'update_channel', + 'delete_channel', + 'get_provider', + 'list_providers', + 'get_channel_connection', + 'list_channel_connections', + 'create_channel_connection', + 'delete_channel_connection', + 'get_google_channel_config', + 'update_google_channel_config', + 'get_message_bus', + 'list_message_buses', + 'list_message_bus_enrollments', + 'create_message_bus', + 'update_message_bus', + 'delete_message_bus', + 'get_enrollment', + 'list_enrollments', + 'create_enrollment', + 'update_enrollment', + 'delete_enrollment', + 'get_pipeline', + 'list_pipelines', + 'create_pipeline', + 'update_pipeline', + 'delete_pipeline', + 'get_google_api_source', + 'list_google_api_sources', + 'create_google_api_source', + 'update_google_api_source', + 'delete_google_api_source', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_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_eventarc_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.eventarc_v1.services.eventarc.transports.EventarcTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EventarcTransport( + 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_eventarc_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.eventarc_v1.services.eventarc.transports.EventarcTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EventarcTransport() + adc.assert_called_once() + + +def test_eventarc_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) + EventarcClient() + 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.EventarcGrpcTransport, + transports.EventarcGrpcAsyncIOTransport, + ], +) +def test_eventarc_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.EventarcGrpcTransport, + transports.EventarcGrpcAsyncIOTransport, + transports.EventarcRestTransport, + ], +) +def test_eventarc_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.EventarcGrpcTransport, grpc_helpers), + (transports.EventarcGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_eventarc_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( + "eventarc.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="eventarc.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EventarcGrpcTransport, transports.EventarcGrpcAsyncIOTransport]) +def test_eventarc_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_eventarc_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.EventarcRestTransport ( + 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_eventarc_host_no_port(transport_name): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='eventarc.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'eventarc.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://eventarc.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_eventarc_host_with_port(transport_name): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='eventarc.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'eventarc.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://eventarc.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_eventarc_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EventarcClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EventarcClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_trigger._session + session2 = client2.transport.get_trigger._session + assert session1 != session2 + session1 = client1.transport.list_triggers._session + session2 = client2.transport.list_triggers._session + assert session1 != session2 + session1 = client1.transport.create_trigger._session + session2 = client2.transport.create_trigger._session + assert session1 != session2 + session1 = client1.transport.update_trigger._session + session2 = client2.transport.update_trigger._session + assert session1 != session2 + session1 = client1.transport.delete_trigger._session + session2 = client2.transport.delete_trigger._session + assert session1 != session2 + session1 = client1.transport.get_channel._session + session2 = client2.transport.get_channel._session + assert session1 != session2 + session1 = client1.transport.list_channels._session + session2 = client2.transport.list_channels._session + assert session1 != session2 + session1 = client1.transport.create_channel_._session + session2 = client2.transport.create_channel_._session + assert session1 != session2 + session1 = client1.transport.update_channel._session + session2 = client2.transport.update_channel._session + assert session1 != session2 + session1 = client1.transport.delete_channel._session + session2 = client2.transport.delete_channel._session + assert session1 != session2 + session1 = client1.transport.get_provider._session + session2 = client2.transport.get_provider._session + assert session1 != session2 + session1 = client1.transport.list_providers._session + session2 = client2.transport.list_providers._session + assert session1 != session2 + session1 = client1.transport.get_channel_connection._session + session2 = client2.transport.get_channel_connection._session + assert session1 != session2 + session1 = client1.transport.list_channel_connections._session + session2 = client2.transport.list_channel_connections._session + assert session1 != session2 + session1 = client1.transport.create_channel_connection._session + session2 = client2.transport.create_channel_connection._session + assert session1 != session2 + session1 = client1.transport.delete_channel_connection._session + session2 = client2.transport.delete_channel_connection._session + assert session1 != session2 + session1 = client1.transport.get_google_channel_config._session + session2 = client2.transport.get_google_channel_config._session + assert session1 != session2 + session1 = client1.transport.update_google_channel_config._session + session2 = client2.transport.update_google_channel_config._session + assert session1 != session2 + session1 = client1.transport.get_message_bus._session + session2 = client2.transport.get_message_bus._session + assert session1 != session2 + session1 = client1.transport.list_message_buses._session + session2 = client2.transport.list_message_buses._session + assert session1 != session2 + session1 = client1.transport.list_message_bus_enrollments._session + session2 = client2.transport.list_message_bus_enrollments._session + assert session1 != session2 + session1 = client1.transport.create_message_bus._session + session2 = client2.transport.create_message_bus._session + assert session1 != session2 + session1 = client1.transport.update_message_bus._session + session2 = client2.transport.update_message_bus._session + assert session1 != session2 + session1 = client1.transport.delete_message_bus._session + session2 = client2.transport.delete_message_bus._session + assert session1 != session2 + session1 = client1.transport.get_enrollment._session + session2 = client2.transport.get_enrollment._session + assert session1 != session2 + session1 = client1.transport.list_enrollments._session + session2 = client2.transport.list_enrollments._session + assert session1 != session2 + session1 = client1.transport.create_enrollment._session + session2 = client2.transport.create_enrollment._session + assert session1 != session2 + session1 = client1.transport.update_enrollment._session + session2 = client2.transport.update_enrollment._session + assert session1 != session2 + session1 = client1.transport.delete_enrollment._session + session2 = client2.transport.delete_enrollment._session + assert session1 != session2 + session1 = client1.transport.get_pipeline._session + session2 = client2.transport.get_pipeline._session + assert session1 != session2 + session1 = client1.transport.list_pipelines._session + session2 = client2.transport.list_pipelines._session + assert session1 != session2 + session1 = client1.transport.create_pipeline._session + session2 = client2.transport.create_pipeline._session + assert session1 != session2 + session1 = client1.transport.update_pipeline._session + session2 = client2.transport.update_pipeline._session + assert session1 != session2 + session1 = client1.transport.delete_pipeline._session + session2 = client2.transport.delete_pipeline._session + assert session1 != session2 + session1 = client1.transport.get_google_api_source._session + session2 = client2.transport.get_google_api_source._session + assert session1 != session2 + session1 = client1.transport.list_google_api_sources._session + session2 = client2.transport.list_google_api_sources._session + assert session1 != session2 + session1 = client1.transport.create_google_api_source._session + session2 = client2.transport.create_google_api_source._session + assert session1 != session2 + session1 = client1.transport.update_google_api_source._session + session2 = client2.transport.update_google_api_source._session + assert session1 != session2 + session1 = client1.transport.delete_google_api_source._session + session2 = client2.transport.delete_google_api_source._session + assert session1 != session2 +def test_eventarc_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EventarcGrpcTransport( + 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_eventarc_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EventarcGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.EventarcGrpcTransport, transports.EventarcGrpcAsyncIOTransport]) +def test_eventarc_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.EventarcGrpcTransport, transports.EventarcGrpcAsyncIOTransport]) +def test_eventarc_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_eventarc_grpc_lro_client(): + client = EventarcClient( + 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_eventarc_grpc_lro_async_client(): + client = EventarcAsyncClient( + 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_channel_path(): + project = "squid" + location = "clam" + channel = "whelk" + expected = "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + actual = EventarcClient.channel_path(project, location, channel) + assert expected == actual + + +def test_parse_channel_path(): + expected = { + "project": "octopus", + "location": "oyster", + "channel": "nudibranch", + } + path = EventarcClient.channel_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_channel_path(path) + assert expected == actual + +def test_channel_connection_path(): + project = "cuttlefish" + location = "mussel" + channel_connection = "winkle" + expected = "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) + actual = EventarcClient.channel_connection_path(project, location, channel_connection) + assert expected == actual + + +def test_parse_channel_connection_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "channel_connection": "abalone", + } + path = EventarcClient.channel_connection_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_channel_connection_path(path) + assert expected == actual + +def test_cloud_function_path(): + project = "squid" + location = "clam" + function = "whelk" + expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + actual = EventarcClient.cloud_function_path(project, location, function) + assert expected == actual + + +def test_parse_cloud_function_path(): + expected = { + "project": "octopus", + "location": "oyster", + "function": "nudibranch", + } + path = EventarcClient.cloud_function_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_cloud_function_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 = EventarcClient.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 = EventarcClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_crypto_key_path(path) + assert expected == actual + +def test_enrollment_path(): + project = "whelk" + location = "octopus" + enrollment = "oyster" + expected = "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) + actual = EventarcClient.enrollment_path(project, location, enrollment) + assert expected == actual + + +def test_parse_enrollment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "enrollment": "mussel", + } + path = EventarcClient.enrollment_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_enrollment_path(path) + assert expected == actual + +def test_google_api_source_path(): + project = "winkle" + location = "nautilus" + google_api_source = "scallop" + expected = "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) + actual = EventarcClient.google_api_source_path(project, location, google_api_source) + assert expected == actual + + +def test_parse_google_api_source_path(): + expected = { + "project": "abalone", + "location": "squid", + "google_api_source": "clam", + } + path = EventarcClient.google_api_source_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_google_api_source_path(path) + assert expected == actual + +def test_google_channel_config_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) + actual = EventarcClient.google_channel_config_path(project, location) + assert expected == actual + + +def test_parse_google_channel_config_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = EventarcClient.google_channel_config_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_google_channel_config_path(path) + assert expected == actual + +def test_message_bus_path(): + project = "cuttlefish" + location = "mussel" + message_bus = "winkle" + expected = "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) + actual = EventarcClient.message_bus_path(project, location, message_bus) + assert expected == actual + + +def test_parse_message_bus_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "message_bus": "abalone", + } + path = EventarcClient.message_bus_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_message_bus_path(path) + assert expected == actual + +def test_network_attachment_path(): + project = "squid" + region = "clam" + networkattachment = "whelk" + expected = "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) + actual = EventarcClient.network_attachment_path(project, region, networkattachment) + assert expected == actual + + +def test_parse_network_attachment_path(): + expected = { + "project": "octopus", + "region": "oyster", + "networkattachment": "nudibranch", + } + path = EventarcClient.network_attachment_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_network_attachment_path(path) + assert expected == actual + +def test_pipeline_path(): + project = "cuttlefish" + location = "mussel" + pipeline = "winkle" + expected = "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) + actual = EventarcClient.pipeline_path(project, location, pipeline) + assert expected == actual + + +def test_parse_pipeline_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "pipeline": "abalone", + } + path = EventarcClient.pipeline_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_pipeline_path(path) + assert expected == actual + +def test_provider_path(): + project = "squid" + location = "clam" + provider = "whelk" + expected = "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) + actual = EventarcClient.provider_path(project, location, provider) + assert expected == actual + + +def test_parse_provider_path(): + expected = { + "project": "octopus", + "location": "oyster", + "provider": "nudibranch", + } + path = EventarcClient.provider_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_provider_path(path) + assert expected == actual + +def test_service_path(): + expected = "*".format() + actual = EventarcClient.service_path() + assert expected == actual + + +def test_parse_service_path(): + expected = { + } + path = EventarcClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_service_path(path) + assert expected == actual + +def test_service_account_path(): + project = "cuttlefish" + service_account = "mussel" + expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + actual = EventarcClient.service_account_path(project, service_account) + assert expected == actual + + +def test_parse_service_account_path(): + expected = { + "project": "winkle", + "service_account": "nautilus", + } + path = EventarcClient.service_account_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_service_account_path(path) + assert expected == actual + +def test_topic_path(): + project = "scallop" + topic = "abalone" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = EventarcClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "squid", + "topic": "clam", + } + path = EventarcClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_topic_path(path) + assert expected == actual + +def test_trigger_path(): + project = "whelk" + location = "octopus" + trigger = "oyster" + expected = "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + actual = EventarcClient.trigger_path(project, location, trigger) + assert expected == actual + + +def test_parse_trigger_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "trigger": "mussel", + } + path = EventarcClient.trigger_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_trigger_path(path) + assert expected == actual + +def test_workflow_path(): + project = "winkle" + location = "nautilus" + workflow = "scallop" + expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + actual = EventarcClient.workflow_path(project, location, workflow) + assert expected == actual + + +def test_parse_workflow_path(): + expected = { + "project": "abalone", + "location": "squid", + "workflow": "clam", + } + path = EventarcClient.workflow_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_workflow_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EventarcClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = EventarcClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = EventarcClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = EventarcClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EventarcClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = EventarcClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = EventarcClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = EventarcClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.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 = EventarcClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = EventarcClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.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.EventarcTransport, '_prep_wrapped_messages') as prep: + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EventarcTransport, '_prep_wrapped_messages') as prep: + transport_class = EventarcClient.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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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_cancel_operation(transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EventarcAsyncClient( + 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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcAsyncClient( + 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 = EventarcClient( + 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 = EventarcClient( + 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", [ + (EventarcClient, transports.EventarcGrpcTransport), + (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport), +]) +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, + ) From 6606c777e5950169339dda65c022b1b6cf32064b Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 12 Nov 2024 21:03:15 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-cloud-eventarc/v1/.coveragerc | 13 - .../google-cloud-eventarc/v1/.flake8 | 33 - .../google-cloud-eventarc/v1/MANIFEST.in | 2 - .../google-cloud-eventarc/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-cloud-eventarc/v1/docs/conf.py | 376 - .../v1/docs/eventarc_v1/eventarc.rst | 10 - .../v1/docs/eventarc_v1/services_.rst | 6 - .../v1/docs/eventarc_v1/types_.rst | 6 - .../google-cloud-eventarc/v1/docs/index.rst | 7 - .../v1/google/cloud/eventarc/__init__.py | 167 - .../v1/google/cloud/eventarc/gapic_version.py | 16 - .../v1/google/cloud/eventarc/py.typed | 2 - .../v1/google/cloud/eventarc_v1/__init__.py | 168 - .../cloud/eventarc_v1/gapic_metadata.json | 613 - .../google/cloud/eventarc_v1/gapic_version.py | 16 - .../v1/google/cloud/eventarc_v1/py.typed | 2 - .../cloud/eventarc_v1/services/__init__.py | 15 - .../eventarc_v1/services/eventarc/__init__.py | 22 - .../services/eventarc/async_client.py | 5726 --- .../eventarc_v1/services/eventarc/client.py | 6147 --- .../eventarc_v1/services/eventarc/pagers.py | 1250 - .../services/eventarc/transports/README.rst | 9 - .../services/eventarc/transports/__init__.py | 38 - .../services/eventarc/transports/base.py | 1013 - .../services/eventarc/transports/grpc.py | 1486 - .../eventarc/transports/grpc_asyncio.py | 1922 - .../services/eventarc/transports/rest.py | 5300 --- .../services/eventarc/transports/rest_base.py | 1996 - .../cloud/eventarc_v1/types/__init__.py | 182 - .../google/cloud/eventarc_v1/types/channel.py | 168 - .../eventarc_v1/types/channel_connection.py | 92 - .../cloud/eventarc_v1/types/discovery.py | 149 - .../cloud/eventarc_v1/types/enrollment.py | 129 - .../cloud/eventarc_v1/types/eventarc.py | 1745 - .../eventarc_v1/types/google_api_source.py | 130 - .../types/google_channel_config.py | 70 - .../cloud/eventarc_v1/types/logging_config.py | 95 - .../cloud/eventarc_v1/types/message_bus.py | 126 - .../cloud/eventarc_v1/types/network_config.py | 47 - .../cloud/eventarc_v1/types/pipeline.py | 838 - .../google/cloud/eventarc_v1/types/trigger.py | 489 - .../google-cloud-eventarc/v1/mypy.ini | 3 - .../google-cloud-eventarc/v1/noxfile.py | 280 - ...generated_eventarc_create_channel_async.py | 62 - ...ventarc_create_channel_connection_async.py | 62 - ...eventarc_create_channel_connection_sync.py | 62 - ..._generated_eventarc_create_channel_sync.py | 62 - ...erated_eventarc_create_enrollment_async.py | 63 - ...nerated_eventarc_create_enrollment_sync.py | 63 - ...eventarc_create_google_api_source_async.py | 61 - ..._eventarc_create_google_api_source_sync.py | 61 - ...rated_eventarc_create_message_bus_async.py | 57 - ...erated_eventarc_create_message_bus_sync.py | 57 - ...enerated_eventarc_create_pipeline_async.py | 61 - ...generated_eventarc_create_pipeline_sync.py | 61 - ...generated_eventarc_create_trigger_async.py | 65 - ..._generated_eventarc_create_trigger_sync.py | 65 - ...generated_eventarc_delete_channel_async.py | 56 - ...ventarc_delete_channel_connection_async.py | 56 - ...eventarc_delete_channel_connection_sync.py | 56 - ..._generated_eventarc_delete_channel_sync.py | 56 - ...erated_eventarc_delete_enrollment_async.py | 56 - ...nerated_eventarc_delete_enrollment_sync.py | 56 - ...eventarc_delete_google_api_source_async.py | 56 - ..._eventarc_delete_google_api_source_sync.py | 56 - ...rated_eventarc_delete_message_bus_async.py | 56 - ...erated_eventarc_delete_message_bus_sync.py | 56 - ...enerated_eventarc_delete_pipeline_async.py | 56 - ...generated_eventarc_delete_pipeline_sync.py | 56 - ...generated_eventarc_delete_trigger_async.py | 56 - ..._generated_eventarc_delete_trigger_sync.py | 56 - ...v1_generated_eventarc_get_channel_async.py | 52 - ...d_eventarc_get_channel_connection_async.py | 52 - ...ed_eventarc_get_channel_connection_sync.py | 52 - ..._v1_generated_eventarc_get_channel_sync.py | 52 - ...generated_eventarc_get_enrollment_async.py | 52 - ..._generated_eventarc_get_enrollment_sync.py | 52 - ...ed_eventarc_get_google_api_source_async.py | 52 - ...ted_eventarc_get_google_api_source_sync.py | 52 - ...ventarc_get_google_channel_config_async.py | 52 - ...eventarc_get_google_channel_config_sync.py | 52 - ...enerated_eventarc_get_message_bus_async.py | 52 - ...generated_eventarc_get_message_bus_sync.py | 52 - ...1_generated_eventarc_get_pipeline_async.py | 52 - ...v1_generated_eventarc_get_pipeline_sync.py | 52 - ...1_generated_eventarc_get_provider_async.py | 52 - ...v1_generated_eventarc_get_provider_sync.py | 52 - ...v1_generated_eventarc_get_trigger_async.py | 52 - ..._v1_generated_eventarc_get_trigger_sync.py | 52 - ...eventarc_list_channel_connections_async.py | 53 - ..._eventarc_list_channel_connections_sync.py | 53 - ..._generated_eventarc_list_channels_async.py | 53 - ...1_generated_eventarc_list_channels_sync.py | 53 - ...nerated_eventarc_list_enrollments_async.py | 53 - ...enerated_eventarc_list_enrollments_sync.py | 53 - ..._eventarc_list_google_api_sources_async.py | 53 - ...d_eventarc_list_google_api_sources_sync.py | 53 - ...tarc_list_message_bus_enrollments_async.py | 53 - ...ntarc_list_message_bus_enrollments_sync.py | 53 - ...rated_eventarc_list_message_buses_async.py | 53 - ...erated_eventarc_list_message_buses_sync.py | 53 - ...generated_eventarc_list_pipelines_async.py | 53 - ..._generated_eventarc_list_pipelines_sync.py | 53 - ...generated_eventarc_list_providers_async.py | 53 - ..._generated_eventarc_list_providers_sync.py | 53 - ..._generated_eventarc_list_triggers_async.py | 53 - ...1_generated_eventarc_list_triggers_sync.py | 53 - ...generated_eventarc_update_channel_async.py | 55 - ..._generated_eventarc_update_channel_sync.py | 55 - ...erated_eventarc_update_enrollment_async.py | 61 - ...nerated_eventarc_update_enrollment_sync.py | 61 - ...eventarc_update_google_api_source_async.py | 59 - ..._eventarc_update_google_api_source_sync.py | 59 - ...tarc_update_google_channel_config_async.py | 55 - ...ntarc_update_google_channel_config_sync.py | 55 - ...rated_eventarc_update_message_bus_async.py | 55 - ...erated_eventarc_update_message_bus_sync.py | 55 - ...enerated_eventarc_update_pipeline_async.py | 59 - ...generated_eventarc_update_pipeline_sync.py | 59 - ...generated_eventarc_update_trigger_async.py | 55 - ..._generated_eventarc_update_trigger_sync.py | 55 - ...pet_metadata_google.cloud.eventarc.v1.json | 6510 --- .../v1/scripts/fixup_eventarc_v1_keywords.py | 214 - .../google-cloud-eventarc/v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/eventarc_v1/__init__.py | 16 - .../unit/gapic/eventarc_v1/test_eventarc.py | 32779 ---------------- .../google/cloud/eventarc/gapic_version.py | 2 +- .../google/cloud/eventarc_v1/gapic_version.py | 2 +- .../cloud/eventarc_v1/types/logging_config.py | 2 +- ...pet_metadata_google.cloud.eventarc.v1.json | 2 +- 141 files changed, 4 insertions(+), 75013 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py diff --git a/owl-bot-staging/google-cloud-eventarc/v1/.coveragerc b/owl-bot-staging/google-cloud-eventarc/v1/.coveragerc deleted file mode 100644 index a0c8f972f201..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/eventarc/__init__.py - google/cloud/eventarc/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-eventarc/v1/.flake8 b/owl-bot-staging/google-cloud-eventarc/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in b/owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in deleted file mode 100644 index a7ef8bafb9c6..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/eventarc *.py -recursive-include google/cloud/eventarc_v1 *.py diff --git a/owl-bot-staging/google-cloud-eventarc/v1/README.rst b/owl-bot-staging/google-cloud-eventarc/v1/README.rst deleted file mode 100644 index 4c79a1d0f7db..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Eventarc API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Eventarc API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py b/owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py deleted file mode 100644 index 4545505bf3da..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-eventarc documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-eventarc" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-eventarc-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-eventarc.tex", - u"google-cloud-eventarc Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-eventarc", - u"Google Cloud Eventarc Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-eventarc", - u"google-cloud-eventarc Documentation", - author, - "google-cloud-eventarc", - "GAPIC library for Google Cloud Eventarc API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst deleted file mode 100644 index 335577a9f38d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/eventarc.rst +++ /dev/null @@ -1,10 +0,0 @@ -Eventarc --------------------------- - -.. automodule:: google.cloud.eventarc_v1.services.eventarc - :members: - :inherited-members: - -.. automodule:: google.cloud.eventarc_v1.services.eventarc.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst deleted file mode 100644 index 7ea77f99bdb4..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Eventarc v1 API -========================================= -.. toctree:: - :maxdepth: 2 - - eventarc diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst deleted file mode 100644 index 5a74926d5bf1..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/docs/eventarc_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Eventarc v1 API -====================================== - -.. automodule:: google.cloud.eventarc_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst b/owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst deleted file mode 100644 index 0a20636626b1..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - eventarc_v1/services_ - eventarc_v1/types_ diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py deleted file mode 100644 index 15978a3966ed..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/__init__.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.eventarc import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.eventarc_v1.services.eventarc.client import EventarcClient -from google.cloud.eventarc_v1.services.eventarc.async_client import EventarcAsyncClient - -from google.cloud.eventarc_v1.types.channel import Channel -from google.cloud.eventarc_v1.types.channel_connection import ChannelConnection -from google.cloud.eventarc_v1.types.discovery import EventType -from google.cloud.eventarc_v1.types.discovery import FilteringAttribute -from google.cloud.eventarc_v1.types.discovery import Provider -from google.cloud.eventarc_v1.types.enrollment import Enrollment -from google.cloud.eventarc_v1.types.eventarc import CreateChannelConnectionRequest -from google.cloud.eventarc_v1.types.eventarc import CreateChannelRequest -from google.cloud.eventarc_v1.types.eventarc import CreateEnrollmentRequest -from google.cloud.eventarc_v1.types.eventarc import CreateGoogleApiSourceRequest -from google.cloud.eventarc_v1.types.eventarc import CreateMessageBusRequest -from google.cloud.eventarc_v1.types.eventarc import CreatePipelineRequest -from google.cloud.eventarc_v1.types.eventarc import CreateTriggerRequest -from google.cloud.eventarc_v1.types.eventarc import DeleteChannelConnectionRequest -from google.cloud.eventarc_v1.types.eventarc import DeleteChannelRequest -from google.cloud.eventarc_v1.types.eventarc import DeleteEnrollmentRequest -from google.cloud.eventarc_v1.types.eventarc import DeleteGoogleApiSourceRequest -from google.cloud.eventarc_v1.types.eventarc import DeleteMessageBusRequest -from google.cloud.eventarc_v1.types.eventarc import DeletePipelineRequest -from google.cloud.eventarc_v1.types.eventarc import DeleteTriggerRequest -from google.cloud.eventarc_v1.types.eventarc import GetChannelConnectionRequest -from google.cloud.eventarc_v1.types.eventarc import GetChannelRequest -from google.cloud.eventarc_v1.types.eventarc import GetEnrollmentRequest -from google.cloud.eventarc_v1.types.eventarc import GetGoogleApiSourceRequest -from google.cloud.eventarc_v1.types.eventarc import GetGoogleChannelConfigRequest -from google.cloud.eventarc_v1.types.eventarc import GetMessageBusRequest -from google.cloud.eventarc_v1.types.eventarc import GetPipelineRequest -from google.cloud.eventarc_v1.types.eventarc import GetProviderRequest -from google.cloud.eventarc_v1.types.eventarc import GetTriggerRequest -from google.cloud.eventarc_v1.types.eventarc import ListChannelConnectionsRequest -from google.cloud.eventarc_v1.types.eventarc import ListChannelConnectionsResponse -from google.cloud.eventarc_v1.types.eventarc import ListChannelsRequest -from google.cloud.eventarc_v1.types.eventarc import ListChannelsResponse -from google.cloud.eventarc_v1.types.eventarc import ListEnrollmentsRequest -from google.cloud.eventarc_v1.types.eventarc import ListEnrollmentsResponse -from google.cloud.eventarc_v1.types.eventarc import ListGoogleApiSourcesRequest -from google.cloud.eventarc_v1.types.eventarc import ListGoogleApiSourcesResponse -from google.cloud.eventarc_v1.types.eventarc import ListMessageBusEnrollmentsRequest -from google.cloud.eventarc_v1.types.eventarc import ListMessageBusEnrollmentsResponse -from google.cloud.eventarc_v1.types.eventarc import ListMessageBusesRequest -from google.cloud.eventarc_v1.types.eventarc import ListMessageBusesResponse -from google.cloud.eventarc_v1.types.eventarc import ListPipelinesRequest -from google.cloud.eventarc_v1.types.eventarc import ListPipelinesResponse -from google.cloud.eventarc_v1.types.eventarc import ListProvidersRequest -from google.cloud.eventarc_v1.types.eventarc import ListProvidersResponse -from google.cloud.eventarc_v1.types.eventarc import ListTriggersRequest -from google.cloud.eventarc_v1.types.eventarc import ListTriggersResponse -from google.cloud.eventarc_v1.types.eventarc import OperationMetadata -from google.cloud.eventarc_v1.types.eventarc import UpdateChannelRequest -from google.cloud.eventarc_v1.types.eventarc import UpdateEnrollmentRequest -from google.cloud.eventarc_v1.types.eventarc import UpdateGoogleApiSourceRequest -from google.cloud.eventarc_v1.types.eventarc import UpdateGoogleChannelConfigRequest -from google.cloud.eventarc_v1.types.eventarc import UpdateMessageBusRequest -from google.cloud.eventarc_v1.types.eventarc import UpdatePipelineRequest -from google.cloud.eventarc_v1.types.eventarc import UpdateTriggerRequest -from google.cloud.eventarc_v1.types.google_api_source import GoogleApiSource -from google.cloud.eventarc_v1.types.google_channel_config import GoogleChannelConfig -from google.cloud.eventarc_v1.types.logging_config import LoggingConfig -from google.cloud.eventarc_v1.types.message_bus import MessageBus -from google.cloud.eventarc_v1.types.network_config import NetworkConfig -from google.cloud.eventarc_v1.types.pipeline import Pipeline -from google.cloud.eventarc_v1.types.trigger import CloudRun -from google.cloud.eventarc_v1.types.trigger import Destination -from google.cloud.eventarc_v1.types.trigger import EventFilter -from google.cloud.eventarc_v1.types.trigger import GKE -from google.cloud.eventarc_v1.types.trigger import HttpEndpoint -from google.cloud.eventarc_v1.types.trigger import Pubsub -from google.cloud.eventarc_v1.types.trigger import StateCondition -from google.cloud.eventarc_v1.types.trigger import Transport -from google.cloud.eventarc_v1.types.trigger import Trigger - -__all__ = ('EventarcClient', - 'EventarcAsyncClient', - 'Channel', - 'ChannelConnection', - 'EventType', - 'FilteringAttribute', - 'Provider', - 'Enrollment', - 'CreateChannelConnectionRequest', - 'CreateChannelRequest', - 'CreateEnrollmentRequest', - 'CreateGoogleApiSourceRequest', - 'CreateMessageBusRequest', - 'CreatePipelineRequest', - 'CreateTriggerRequest', - 'DeleteChannelConnectionRequest', - 'DeleteChannelRequest', - 'DeleteEnrollmentRequest', - 'DeleteGoogleApiSourceRequest', - 'DeleteMessageBusRequest', - 'DeletePipelineRequest', - 'DeleteTriggerRequest', - 'GetChannelConnectionRequest', - 'GetChannelRequest', - 'GetEnrollmentRequest', - 'GetGoogleApiSourceRequest', - 'GetGoogleChannelConfigRequest', - 'GetMessageBusRequest', - 'GetPipelineRequest', - 'GetProviderRequest', - 'GetTriggerRequest', - 'ListChannelConnectionsRequest', - 'ListChannelConnectionsResponse', - 'ListChannelsRequest', - 'ListChannelsResponse', - 'ListEnrollmentsRequest', - 'ListEnrollmentsResponse', - 'ListGoogleApiSourcesRequest', - 'ListGoogleApiSourcesResponse', - 'ListMessageBusEnrollmentsRequest', - 'ListMessageBusEnrollmentsResponse', - 'ListMessageBusesRequest', - 'ListMessageBusesResponse', - 'ListPipelinesRequest', - 'ListPipelinesResponse', - 'ListProvidersRequest', - 'ListProvidersResponse', - 'ListTriggersRequest', - 'ListTriggersResponse', - 'OperationMetadata', - 'UpdateChannelRequest', - 'UpdateEnrollmentRequest', - 'UpdateGoogleApiSourceRequest', - 'UpdateGoogleChannelConfigRequest', - 'UpdateMessageBusRequest', - 'UpdatePipelineRequest', - 'UpdateTriggerRequest', - 'GoogleApiSource', - 'GoogleChannelConfig', - 'LoggingConfig', - 'MessageBus', - 'NetworkConfig', - 'Pipeline', - 'CloudRun', - 'Destination', - 'EventFilter', - 'GKE', - 'HttpEndpoint', - 'Pubsub', - 'StateCondition', - 'Transport', - 'Trigger', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed deleted file mode 100644 index ccbcd1359343..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-eventarc package uses inline types. diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py deleted file mode 100644 index eded7ed9c6fe..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/__init__.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.eventarc_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.eventarc import EventarcClient -from .services.eventarc import EventarcAsyncClient - -from .types.channel import Channel -from .types.channel_connection import ChannelConnection -from .types.discovery import EventType -from .types.discovery import FilteringAttribute -from .types.discovery import Provider -from .types.enrollment import Enrollment -from .types.eventarc import CreateChannelConnectionRequest -from .types.eventarc import CreateChannelRequest -from .types.eventarc import CreateEnrollmentRequest -from .types.eventarc import CreateGoogleApiSourceRequest -from .types.eventarc import CreateMessageBusRequest -from .types.eventarc import CreatePipelineRequest -from .types.eventarc import CreateTriggerRequest -from .types.eventarc import DeleteChannelConnectionRequest -from .types.eventarc import DeleteChannelRequest -from .types.eventarc import DeleteEnrollmentRequest -from .types.eventarc import DeleteGoogleApiSourceRequest -from .types.eventarc import DeleteMessageBusRequest -from .types.eventarc import DeletePipelineRequest -from .types.eventarc import DeleteTriggerRequest -from .types.eventarc import GetChannelConnectionRequest -from .types.eventarc import GetChannelRequest -from .types.eventarc import GetEnrollmentRequest -from .types.eventarc import GetGoogleApiSourceRequest -from .types.eventarc import GetGoogleChannelConfigRequest -from .types.eventarc import GetMessageBusRequest -from .types.eventarc import GetPipelineRequest -from .types.eventarc import GetProviderRequest -from .types.eventarc import GetTriggerRequest -from .types.eventarc import ListChannelConnectionsRequest -from .types.eventarc import ListChannelConnectionsResponse -from .types.eventarc import ListChannelsRequest -from .types.eventarc import ListChannelsResponse -from .types.eventarc import ListEnrollmentsRequest -from .types.eventarc import ListEnrollmentsResponse -from .types.eventarc import ListGoogleApiSourcesRequest -from .types.eventarc import ListGoogleApiSourcesResponse -from .types.eventarc import ListMessageBusEnrollmentsRequest -from .types.eventarc import ListMessageBusEnrollmentsResponse -from .types.eventarc import ListMessageBusesRequest -from .types.eventarc import ListMessageBusesResponse -from .types.eventarc import ListPipelinesRequest -from .types.eventarc import ListPipelinesResponse -from .types.eventarc import ListProvidersRequest -from .types.eventarc import ListProvidersResponse -from .types.eventarc import ListTriggersRequest -from .types.eventarc import ListTriggersResponse -from .types.eventarc import OperationMetadata -from .types.eventarc import UpdateChannelRequest -from .types.eventarc import UpdateEnrollmentRequest -from .types.eventarc import UpdateGoogleApiSourceRequest -from .types.eventarc import UpdateGoogleChannelConfigRequest -from .types.eventarc import UpdateMessageBusRequest -from .types.eventarc import UpdatePipelineRequest -from .types.eventarc import UpdateTriggerRequest -from .types.google_api_source import GoogleApiSource -from .types.google_channel_config import GoogleChannelConfig -from .types.logging_config import LoggingConfig -from .types.message_bus import MessageBus -from .types.network_config import NetworkConfig -from .types.pipeline import Pipeline -from .types.trigger import CloudRun -from .types.trigger import Destination -from .types.trigger import EventFilter -from .types.trigger import GKE -from .types.trigger import HttpEndpoint -from .types.trigger import Pubsub -from .types.trigger import StateCondition -from .types.trigger import Transport -from .types.trigger import Trigger - -__all__ = ( - 'EventarcAsyncClient', -'Channel', -'ChannelConnection', -'CloudRun', -'CreateChannelConnectionRequest', -'CreateChannelRequest', -'CreateEnrollmentRequest', -'CreateGoogleApiSourceRequest', -'CreateMessageBusRequest', -'CreatePipelineRequest', -'CreateTriggerRequest', -'DeleteChannelConnectionRequest', -'DeleteChannelRequest', -'DeleteEnrollmentRequest', -'DeleteGoogleApiSourceRequest', -'DeleteMessageBusRequest', -'DeletePipelineRequest', -'DeleteTriggerRequest', -'Destination', -'Enrollment', -'EventFilter', -'EventType', -'EventarcClient', -'FilteringAttribute', -'GKE', -'GetChannelConnectionRequest', -'GetChannelRequest', -'GetEnrollmentRequest', -'GetGoogleApiSourceRequest', -'GetGoogleChannelConfigRequest', -'GetMessageBusRequest', -'GetPipelineRequest', -'GetProviderRequest', -'GetTriggerRequest', -'GoogleApiSource', -'GoogleChannelConfig', -'HttpEndpoint', -'ListChannelConnectionsRequest', -'ListChannelConnectionsResponse', -'ListChannelsRequest', -'ListChannelsResponse', -'ListEnrollmentsRequest', -'ListEnrollmentsResponse', -'ListGoogleApiSourcesRequest', -'ListGoogleApiSourcesResponse', -'ListMessageBusEnrollmentsRequest', -'ListMessageBusEnrollmentsResponse', -'ListMessageBusesRequest', -'ListMessageBusesResponse', -'ListPipelinesRequest', -'ListPipelinesResponse', -'ListProvidersRequest', -'ListProvidersResponse', -'ListTriggersRequest', -'ListTriggersResponse', -'LoggingConfig', -'MessageBus', -'NetworkConfig', -'OperationMetadata', -'Pipeline', -'Provider', -'Pubsub', -'StateCondition', -'Transport', -'Trigger', -'UpdateChannelRequest', -'UpdateEnrollmentRequest', -'UpdateGoogleApiSourceRequest', -'UpdateGoogleChannelConfigRequest', -'UpdateMessageBusRequest', -'UpdatePipelineRequest', -'UpdateTriggerRequest', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json deleted file mode 100644 index 0f7262654380..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_metadata.json +++ /dev/null @@ -1,613 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.eventarc_v1", - "protoPackage": "google.cloud.eventarc.v1", - "schema": "1.0", - "services": { - "Eventarc": { - "clients": { - "grpc": { - "libraryClient": "EventarcClient", - "rpcs": { - "CreateChannel": { - "methods": [ - "create_channel" - ] - }, - "CreateChannelConnection": { - "methods": [ - "create_channel_connection" - ] - }, - "CreateEnrollment": { - "methods": [ - "create_enrollment" - ] - }, - "CreateGoogleApiSource": { - "methods": [ - "create_google_api_source" - ] - }, - "CreateMessageBus": { - "methods": [ - "create_message_bus" - ] - }, - "CreatePipeline": { - "methods": [ - "create_pipeline" - ] - }, - "CreateTrigger": { - "methods": [ - "create_trigger" - ] - }, - "DeleteChannel": { - "methods": [ - "delete_channel" - ] - }, - "DeleteChannelConnection": { - "methods": [ - "delete_channel_connection" - ] - }, - "DeleteEnrollment": { - "methods": [ - "delete_enrollment" - ] - }, - "DeleteGoogleApiSource": { - "methods": [ - "delete_google_api_source" - ] - }, - "DeleteMessageBus": { - "methods": [ - "delete_message_bus" - ] - }, - "DeletePipeline": { - "methods": [ - "delete_pipeline" - ] - }, - "DeleteTrigger": { - "methods": [ - "delete_trigger" - ] - }, - "GetChannel": { - "methods": [ - "get_channel" - ] - }, - "GetChannelConnection": { - "methods": [ - "get_channel_connection" - ] - }, - "GetEnrollment": { - "methods": [ - "get_enrollment" - ] - }, - "GetGoogleApiSource": { - "methods": [ - "get_google_api_source" - ] - }, - "GetGoogleChannelConfig": { - "methods": [ - "get_google_channel_config" - ] - }, - "GetMessageBus": { - "methods": [ - "get_message_bus" - ] - }, - "GetPipeline": { - "methods": [ - "get_pipeline" - ] - }, - "GetProvider": { - "methods": [ - "get_provider" - ] - }, - "GetTrigger": { - "methods": [ - "get_trigger" - ] - }, - "ListChannelConnections": { - "methods": [ - "list_channel_connections" - ] - }, - "ListChannels": { - "methods": [ - "list_channels" - ] - }, - "ListEnrollments": { - "methods": [ - "list_enrollments" - ] - }, - "ListGoogleApiSources": { - "methods": [ - "list_google_api_sources" - ] - }, - "ListMessageBusEnrollments": { - "methods": [ - "list_message_bus_enrollments" - ] - }, - "ListMessageBuses": { - "methods": [ - "list_message_buses" - ] - }, - "ListPipelines": { - "methods": [ - "list_pipelines" - ] - }, - "ListProviders": { - "methods": [ - "list_providers" - ] - }, - "ListTriggers": { - "methods": [ - "list_triggers" - ] - }, - "UpdateChannel": { - "methods": [ - "update_channel" - ] - }, - "UpdateEnrollment": { - "methods": [ - "update_enrollment" - ] - }, - "UpdateGoogleApiSource": { - "methods": [ - "update_google_api_source" - ] - }, - "UpdateGoogleChannelConfig": { - "methods": [ - "update_google_channel_config" - ] - }, - "UpdateMessageBus": { - "methods": [ - "update_message_bus" - ] - }, - "UpdatePipeline": { - "methods": [ - "update_pipeline" - ] - }, - "UpdateTrigger": { - "methods": [ - "update_trigger" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EventarcAsyncClient", - "rpcs": { - "CreateChannel": { - "methods": [ - "create_channel" - ] - }, - "CreateChannelConnection": { - "methods": [ - "create_channel_connection" - ] - }, - "CreateEnrollment": { - "methods": [ - "create_enrollment" - ] - }, - "CreateGoogleApiSource": { - "methods": [ - "create_google_api_source" - ] - }, - "CreateMessageBus": { - "methods": [ - "create_message_bus" - ] - }, - "CreatePipeline": { - "methods": [ - "create_pipeline" - ] - }, - "CreateTrigger": { - "methods": [ - "create_trigger" - ] - }, - "DeleteChannel": { - "methods": [ - "delete_channel" - ] - }, - "DeleteChannelConnection": { - "methods": [ - "delete_channel_connection" - ] - }, - "DeleteEnrollment": { - "methods": [ - "delete_enrollment" - ] - }, - "DeleteGoogleApiSource": { - "methods": [ - "delete_google_api_source" - ] - }, - "DeleteMessageBus": { - "methods": [ - "delete_message_bus" - ] - }, - "DeletePipeline": { - "methods": [ - "delete_pipeline" - ] - }, - "DeleteTrigger": { - "methods": [ - "delete_trigger" - ] - }, - "GetChannel": { - "methods": [ - "get_channel" - ] - }, - "GetChannelConnection": { - "methods": [ - "get_channel_connection" - ] - }, - "GetEnrollment": { - "methods": [ - "get_enrollment" - ] - }, - "GetGoogleApiSource": { - "methods": [ - "get_google_api_source" - ] - }, - "GetGoogleChannelConfig": { - "methods": [ - "get_google_channel_config" - ] - }, - "GetMessageBus": { - "methods": [ - "get_message_bus" - ] - }, - "GetPipeline": { - "methods": [ - "get_pipeline" - ] - }, - "GetProvider": { - "methods": [ - "get_provider" - ] - }, - "GetTrigger": { - "methods": [ - "get_trigger" - ] - }, - "ListChannelConnections": { - "methods": [ - "list_channel_connections" - ] - }, - "ListChannels": { - "methods": [ - "list_channels" - ] - }, - "ListEnrollments": { - "methods": [ - "list_enrollments" - ] - }, - "ListGoogleApiSources": { - "methods": [ - "list_google_api_sources" - ] - }, - "ListMessageBusEnrollments": { - "methods": [ - "list_message_bus_enrollments" - ] - }, - "ListMessageBuses": { - "methods": [ - "list_message_buses" - ] - }, - "ListPipelines": { - "methods": [ - "list_pipelines" - ] - }, - "ListProviders": { - "methods": [ - "list_providers" - ] - }, - "ListTriggers": { - "methods": [ - "list_triggers" - ] - }, - "UpdateChannel": { - "methods": [ - "update_channel" - ] - }, - "UpdateEnrollment": { - "methods": [ - "update_enrollment" - ] - }, - "UpdateGoogleApiSource": { - "methods": [ - "update_google_api_source" - ] - }, - "UpdateGoogleChannelConfig": { - "methods": [ - "update_google_channel_config" - ] - }, - "UpdateMessageBus": { - "methods": [ - "update_message_bus" - ] - }, - "UpdatePipeline": { - "methods": [ - "update_pipeline" - ] - }, - "UpdateTrigger": { - "methods": [ - "update_trigger" - ] - } - } - }, - "rest": { - "libraryClient": "EventarcClient", - "rpcs": { - "CreateChannel": { - "methods": [ - "create_channel" - ] - }, - "CreateChannelConnection": { - "methods": [ - "create_channel_connection" - ] - }, - "CreateEnrollment": { - "methods": [ - "create_enrollment" - ] - }, - "CreateGoogleApiSource": { - "methods": [ - "create_google_api_source" - ] - }, - "CreateMessageBus": { - "methods": [ - "create_message_bus" - ] - }, - "CreatePipeline": { - "methods": [ - "create_pipeline" - ] - }, - "CreateTrigger": { - "methods": [ - "create_trigger" - ] - }, - "DeleteChannel": { - "methods": [ - "delete_channel" - ] - }, - "DeleteChannelConnection": { - "methods": [ - "delete_channel_connection" - ] - }, - "DeleteEnrollment": { - "methods": [ - "delete_enrollment" - ] - }, - "DeleteGoogleApiSource": { - "methods": [ - "delete_google_api_source" - ] - }, - "DeleteMessageBus": { - "methods": [ - "delete_message_bus" - ] - }, - "DeletePipeline": { - "methods": [ - "delete_pipeline" - ] - }, - "DeleteTrigger": { - "methods": [ - "delete_trigger" - ] - }, - "GetChannel": { - "methods": [ - "get_channel" - ] - }, - "GetChannelConnection": { - "methods": [ - "get_channel_connection" - ] - }, - "GetEnrollment": { - "methods": [ - "get_enrollment" - ] - }, - "GetGoogleApiSource": { - "methods": [ - "get_google_api_source" - ] - }, - "GetGoogleChannelConfig": { - "methods": [ - "get_google_channel_config" - ] - }, - "GetMessageBus": { - "methods": [ - "get_message_bus" - ] - }, - "GetPipeline": { - "methods": [ - "get_pipeline" - ] - }, - "GetProvider": { - "methods": [ - "get_provider" - ] - }, - "GetTrigger": { - "methods": [ - "get_trigger" - ] - }, - "ListChannelConnections": { - "methods": [ - "list_channel_connections" - ] - }, - "ListChannels": { - "methods": [ - "list_channels" - ] - }, - "ListEnrollments": { - "methods": [ - "list_enrollments" - ] - }, - "ListGoogleApiSources": { - "methods": [ - "list_google_api_sources" - ] - }, - "ListMessageBusEnrollments": { - "methods": [ - "list_message_bus_enrollments" - ] - }, - "ListMessageBuses": { - "methods": [ - "list_message_buses" - ] - }, - "ListPipelines": { - "methods": [ - "list_pipelines" - ] - }, - "ListProviders": { - "methods": [ - "list_providers" - ] - }, - "ListTriggers": { - "methods": [ - "list_triggers" - ] - }, - "UpdateChannel": { - "methods": [ - "update_channel" - ] - }, - "UpdateEnrollment": { - "methods": [ - "update_enrollment" - ] - }, - "UpdateGoogleApiSource": { - "methods": [ - "update_google_api_source" - ] - }, - "UpdateGoogleChannelConfig": { - "methods": [ - "update_google_channel_config" - ] - }, - "UpdateMessageBus": { - "methods": [ - "update_message_bus" - ] - }, - "UpdatePipeline": { - "methods": [ - "update_pipeline" - ] - }, - "UpdateTrigger": { - "methods": [ - "update_trigger" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed deleted file mode 100644 index ccbcd1359343..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-eventarc package uses inline types. diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py deleted file mode 100644 index 6c6ea026d4bc..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import EventarcClient -from .async_client import EventarcAsyncClient - -__all__ = ( - 'EventarcClient', - 'EventarcAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py deleted file mode 100644 index e2c8f4067103..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/async_client.py +++ /dev/null @@ -1,5726 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.eventarc_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -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.eventarc_v1.services.eventarc import pagers -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel as gce_channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import enrollment as gce_enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import logging_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import message_bus as gce_message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import pipeline as gce_pipeline -from google.cloud.eventarc_v1.types import trigger -from google.cloud.eventarc_v1.types import trigger as gce_trigger -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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EventarcTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EventarcGrpcAsyncIOTransport -from .client import EventarcClient - - -class EventarcAsyncClient: - """Eventarc allows users to subscribe to various events that are - provided by Google Cloud services and forward them to supported - destinations. - """ - - _client: EventarcClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EventarcClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EventarcClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EventarcClient._DEFAULT_UNIVERSE - - channel_path = staticmethod(EventarcClient.channel_path) - parse_channel_path = staticmethod(EventarcClient.parse_channel_path) - channel_connection_path = staticmethod(EventarcClient.channel_connection_path) - parse_channel_connection_path = staticmethod(EventarcClient.parse_channel_connection_path) - cloud_function_path = staticmethod(EventarcClient.cloud_function_path) - parse_cloud_function_path = staticmethod(EventarcClient.parse_cloud_function_path) - crypto_key_path = staticmethod(EventarcClient.crypto_key_path) - parse_crypto_key_path = staticmethod(EventarcClient.parse_crypto_key_path) - enrollment_path = staticmethod(EventarcClient.enrollment_path) - parse_enrollment_path = staticmethod(EventarcClient.parse_enrollment_path) - google_api_source_path = staticmethod(EventarcClient.google_api_source_path) - parse_google_api_source_path = staticmethod(EventarcClient.parse_google_api_source_path) - google_channel_config_path = staticmethod(EventarcClient.google_channel_config_path) - parse_google_channel_config_path = staticmethod(EventarcClient.parse_google_channel_config_path) - message_bus_path = staticmethod(EventarcClient.message_bus_path) - parse_message_bus_path = staticmethod(EventarcClient.parse_message_bus_path) - network_attachment_path = staticmethod(EventarcClient.network_attachment_path) - parse_network_attachment_path = staticmethod(EventarcClient.parse_network_attachment_path) - pipeline_path = staticmethod(EventarcClient.pipeline_path) - parse_pipeline_path = staticmethod(EventarcClient.parse_pipeline_path) - provider_path = staticmethod(EventarcClient.provider_path) - parse_provider_path = staticmethod(EventarcClient.parse_provider_path) - service_path = staticmethod(EventarcClient.service_path) - parse_service_path = staticmethod(EventarcClient.parse_service_path) - service_account_path = staticmethod(EventarcClient.service_account_path) - parse_service_account_path = staticmethod(EventarcClient.parse_service_account_path) - topic_path = staticmethod(EventarcClient.topic_path) - parse_topic_path = staticmethod(EventarcClient.parse_topic_path) - trigger_path = staticmethod(EventarcClient.trigger_path) - parse_trigger_path = staticmethod(EventarcClient.parse_trigger_path) - workflow_path = staticmethod(EventarcClient.workflow_path) - parse_workflow_path = staticmethod(EventarcClient.parse_workflow_path) - common_billing_account_path = staticmethod(EventarcClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EventarcClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EventarcClient.common_folder_path) - parse_common_folder_path = staticmethod(EventarcClient.parse_common_folder_path) - common_organization_path = staticmethod(EventarcClient.common_organization_path) - parse_common_organization_path = staticmethod(EventarcClient.parse_common_organization_path) - common_project_path = staticmethod(EventarcClient.common_project_path) - parse_common_project_path = staticmethod(EventarcClient.parse_common_project_path) - common_location_path = staticmethod(EventarcClient.common_location_path) - parse_common_location_path = staticmethod(EventarcClient.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: - EventarcAsyncClient: The constructed client. - """ - return EventarcClient.from_service_account_info.__func__(EventarcAsyncClient, 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: - EventarcAsyncClient: The constructed client. - """ - return EventarcClient.from_service_account_file.__func__(EventarcAsyncClient, 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 EventarcClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EventarcTransport: - """Returns the transport used by the client instance. - - Returns: - EventarcTransport: 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 = EventarcClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EventarcTransport, Callable[..., EventarcTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the eventarc 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,EventarcTransport,Callable[..., EventarcTransport]]]): - 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 EventarcTransport 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 = EventarcClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_trigger(self, - request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trigger.Trigger: - r"""Get a single trigger. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetTriggerRequest( - name="name_value", - ) - - # Make the request - response = await client.get_trigger(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetTriggerRequest, dict]]): - The request object. The request message for the - GetTrigger method. - name (:class:`str`): - Required. The name of the trigger 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Trigger: - A representation of the trigger - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetTriggerRequest): - request = eventarc.GetTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_trigger] - - # Certain 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_triggers(self, - request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTriggersAsyncPager: - r"""List triggers. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_triggers(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListTriggersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_triggers(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListTriggersRequest, dict]]): - The request object. The request message for the - ListTriggers method. - parent (:class:`str`): - Required. The parent collection to - list triggers on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersAsyncPager: - The response message for the ListTriggers method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListTriggersRequest): - request = eventarc.ListTriggersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_triggers] - - # Certain 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.ListTriggersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_trigger(self, - request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, - *, - parent: Optional[str] = None, - trigger: Optional[gce_trigger.Trigger] = None, - trigger_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new trigger in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - trigger = eventarc_v1.Trigger() - trigger.name = "name_value" - trigger.event_filters.attribute = "attribute_value" - trigger.event_filters.value = "value_value" - trigger.destination.cloud_run.service = "service_value" - trigger.destination.cloud_run.region = "region_value" - - request = eventarc_v1.CreateTriggerRequest( - parent="parent_value", - trigger=trigger, - trigger_id="trigger_id_value", - ) - - # Make the request - operation = client.create_trigger(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreateTriggerRequest, dict]]): - The request object. The request message for the - CreateTrigger method. - parent (:class:`str`): - Required. The parent collection in - which to add this trigger. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger (:class:`google.cloud.eventarc_v1.types.Trigger`): - Required. The trigger to create. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (:class:`str`): - Required. The user-provided ID to be - assigned to the trigger. - - This corresponds to the ``trigger_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Trigger` A - representation of the trigger resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, trigger, trigger_id]) - if request is 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, eventarc.CreateTriggerRequest): - request = eventarc.CreateTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if trigger is not None: - request.trigger = trigger - if trigger_id is not None: - request.trigger_id = trigger_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_trigger] - - # Certain 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, - gce_trigger.Trigger, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_trigger(self, - request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, - *, - trigger: Optional[gce_trigger.Trigger] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update a single trigger. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateTriggerRequest( - ) - - # Make the request - operation = client.update_trigger(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdateTriggerRequest, dict]]): - The request object. The request message for the - UpdateTrigger method. - trigger (:class:`google.cloud.eventarc_v1.types.Trigger`): - The trigger to be updated. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update - all fields, provide a field mask of "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - allow_missing (:class:`bool`): - If set to true, and the trigger is not found, a new - trigger will be created. In this situation, - ``update_mask`` is ignored. - - This corresponds to the ``allow_missing`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Trigger` A - representation of the trigger resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([trigger, update_mask, allow_missing]) - if request is 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, eventarc.UpdateTriggerRequest): - request = eventarc.UpdateTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if trigger is not None: - request.trigger = trigger - if update_mask is not None: - request.update_mask = update_mask - if allow_missing is not None: - request.allow_missing = allow_missing - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_trigger] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("trigger.name", request.trigger.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, - gce_trigger.Trigger, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_trigger(self, - request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single trigger. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteTriggerRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_trigger(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeleteTriggerRequest, dict]]): - The request object. The request message for the - DeleteTrigger method. - name (:class:`str`): - Required. The name of the trigger to - be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - allow_missing (:class:`bool`): - If set to true, and the trigger is - not found, the request will succeed but - no action will be taken on the server. - - This corresponds to the ``allow_missing`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Trigger` A - representation of the trigger resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, allow_missing]) - if request is 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, eventarc.DeleteTriggerRequest): - request = eventarc.DeleteTriggerRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if allow_missing is not None: - request.allow_missing = allow_missing - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_trigger] - - # Certain 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, - trigger.Trigger, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_channel(self, - request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> channel.Channel: - r"""Get a single Channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelRequest( - name="name_value", - ) - - # Make the request - response = await client.get_channel(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetChannelRequest, dict]]): - The request object. The request message for the - GetChannel method. - name (:class:`str`): - Required. The name of the channel 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Channel: - A representation of the Channel - resource. A Channel is a resource on - which event providers publish their - events. The published events are - delivered through the transport - associated with the channel. Note that a - channel is associated with exactly one - event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetChannelRequest): - request = eventarc.GetChannelRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_channel] - - # Certain 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_channels(self, - request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListChannelsAsyncPager: - r"""List channels. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_channels(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channels(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListChannelsRequest, dict]]): - The request object. The request message for the - ListChannels method. - parent (:class:`str`): - Required. The parent collection to - list channels on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsAsyncPager: - The response message for the ListChannels method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListChannelsRequest): - request = eventarc.ListChannelsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_channels] - - # Certain 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.ListChannelsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_channel(self, - request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel: Optional[gce_channel.Channel] = None, - channel_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new channel in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - channel = eventarc_v1.Channel() - channel.pubsub_topic = "pubsub_topic_value" - channel.name = "name_value" - - request = eventarc_v1.CreateChannelRequest( - parent="parent_value", - channel=channel, - channel_id="channel_id_value", - ) - - # Make the request - operation = client.create_channel(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreateChannelRequest, dict]]): - The request object. The request message for the - CreateChannel method. - parent (:class:`str`): - Required. The parent collection in - which to add this channel. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel (:class:`google.cloud.eventarc_v1.types.Channel`): - Required. The channel to create. - This corresponds to the ``channel`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel_id (:class:`str`): - Required. The user-provided ID to be - assigned to the channel. - - This corresponds to the ``channel_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. - A Channel is a resource on which event providers - publish their events. The published events are - delivered through the transport associated with the - channel. Note that a channel is associated with - exactly one event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, channel, channel_id]) - if request is 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, eventarc.CreateChannelRequest): - request = eventarc.CreateChannelRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if channel is not None: - request.channel = channel - if channel_id is not None: - request.channel_id = channel_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_channel_] - - # Certain 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, - gce_channel.Channel, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_channel(self, - request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, - *, - channel: Optional[gce_channel.Channel] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update a single channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateChannelRequest( - ) - - # Make the request - operation = client.update_channel(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdateChannelRequest, dict]]): - The request object. The request message for the - UpdateChannel method. - channel (:class:`google.cloud.eventarc_v1.types.Channel`): - The channel to be updated. - This corresponds to the ``channel`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update - all fields, provide a field mask of "*". - - This 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. - A Channel is a resource on which event providers - publish their events. The published events are - delivered through the transport associated with the - channel. Note that a channel is associated with - exactly one event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([channel, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.UpdateChannelRequest): - request = eventarc.UpdateChannelRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if channel is not None: - request.channel = channel - 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_channel] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("channel.name", request.channel.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, - gce_channel.Channel, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_channel(self, - request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeleteChannelRequest, dict]]): - The request object. The request message for the - DeleteChannel method. - name (:class:`str`): - Required. The name of the channel to - be deleted. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. - A Channel is a resource on which event providers - publish their events. The published events are - delivered through the transport associated with the - channel. Note that a channel is associated with - exactly one event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.DeleteChannelRequest): - request = eventarc.DeleteChannelRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_channel] - - # Certain 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, - channel.Channel, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_provider(self, - request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> discovery.Provider: - r"""Get a single Provider. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_provider(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetProviderRequest( - name="name_value", - ) - - # Make the request - response = await client.get_provider(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetProviderRequest, dict]]): - The request object. The request message for the - GetProvider method. - name (:class:`str`): - Required. The name of the provider 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Provider: - A representation of the Provider - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetProviderRequest): - request = eventarc.GetProviderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_provider] - - # Certain 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_providers(self, - request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProvidersAsyncPager: - r"""List providers. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_providers(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_providers(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListProvidersRequest, dict]]): - The request object. The request message for the - ListProviders method. - parent (:class:`str`): - Required. The parent of the provider - to get. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersAsyncPager: - The response message for the ListProviders method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListProvidersRequest): - request = eventarc.ListProvidersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_providers] - - # Certain 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.ListProvidersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_channel_connection(self, - request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> channel_connection.ChannelConnection: - r"""Get a single ChannelConnection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_channel_connection(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelConnectionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_channel_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetChannelConnectionRequest, dict]]): - The request object. The request message for the - GetChannelConnection method. - name (:class:`str`): - Required. The name of the channel - connection 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.ChannelConnection: - A representation of the - ChannelConnection resource. A - ChannelConnection is a resource which - event providers create during the - activation process to establish a - connection between the provider and the - subscriber channel. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetChannelConnectionRequest): - request = eventarc.GetChannelConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_channel_connection] - - # Certain 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_channel_connections(self, - request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListChannelConnectionsAsyncPager: - r"""List channel connections. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_channel_connections(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channel_connections(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListChannelConnectionsRequest, dict]]): - The request object. The request message for the - ListChannelConnections method. - parent (:class:`str`): - Required. The parent collection from - which to list channel connections. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsAsyncPager: - The response message for the ListChannelConnections - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListChannelConnectionsRequest): - request = eventarc.ListChannelConnectionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_channel_connections] - - # Certain 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.ListChannelConnectionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_channel_connection(self, - request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, - channel_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new ChannelConnection in a particular - project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_channel_connection(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - channel_connection = eventarc_v1.ChannelConnection() - channel_connection.name = "name_value" - channel_connection.channel = "channel_value" - - request = eventarc_v1.CreateChannelConnectionRequest( - parent="parent_value", - channel_connection=channel_connection, - channel_connection_id="channel_connection_id_value", - ) - - # Make the request - operation = client.create_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreateChannelConnectionRequest, dict]]): - The request object. The request message for the - CreateChannelConnection method. - parent (:class:`str`): - Required. The parent collection in - which to add this channel connection. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel_connection (:class:`google.cloud.eventarc_v1.types.ChannelConnection`): - Required. Channel connection to - create. - - This corresponds to the ``channel_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel_connection_id (:class:`str`): - Required. The user-provided ID to be - assigned to the channel connection. - - This corresponds to the ``channel_connection_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. - A ChannelConnection is a resource which event - providers create during the activation process to - establish a connection between the provider and the - subscriber channel. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, channel_connection, channel_connection_id]) - if request is 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, eventarc.CreateChannelConnectionRequest): - request = eventarc.CreateChannelConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if channel_connection is not None: - request.channel_connection = channel_connection - if channel_connection_id is not None: - request.channel_connection_id = channel_connection_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_channel_connection] - - # Certain 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, - gce_channel_connection.ChannelConnection, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_channel_connection(self, - request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single ChannelConnection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_channel_connection(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest, dict]]): - The request object. The request message for the - DeleteChannelConnection method. - name (:class:`str`): - Required. The name of the channel - connection 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. - A ChannelConnection is a resource which event - providers create during the activation process to - establish a connection between the provider and the - subscriber channel. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.DeleteChannelConnectionRequest): - request = eventarc.DeleteChannelConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_channel_connection] - - # Certain 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, - channel_connection.ChannelConnection, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_google_channel_config(self, - request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> google_channel_config.GoogleChannelConfig: - r"""Get a GoogleChannelConfig - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleChannelConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_google_channel_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest, dict]]): - The request object. The request message for the - GetGoogleChannelConfig method. - name (:class:`str`): - Required. The name of the config 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetGoogleChannelConfigRequest): - request = eventarc.GetGoogleChannelConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_google_channel_config] - - # Certain 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_google_channel_config(self, - request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, - *, - google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: - r"""Update a single GoogleChannelConfig - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - google_channel_config = eventarc_v1.GoogleChannelConfig() - google_channel_config.name = "name_value" - - request = eventarc_v1.UpdateGoogleChannelConfigRequest( - google_channel_config=google_channel_config, - ) - - # Make the request - response = await client.update_google_channel_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest, dict]]): - The request object. The request message for the - UpdateGoogleChannelConfig method. - google_channel_config (:class:`google.cloud.eventarc_v1.types.GoogleChannelConfig`): - Required. The config to be updated. - This corresponds to the ``google_channel_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update - all fields, provide a field mask of "*". - - This 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([google_channel_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.UpdateGoogleChannelConfigRequest): - request = eventarc.UpdateGoogleChannelConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if google_channel_config is not None: - request.google_channel_config = google_channel_config - 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_google_channel_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_channel_config.name", request.google_channel_config.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_message_bus(self, - request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> message_bus.MessageBus: - r"""Get a single MessageBus. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetMessageBusRequest( - name="name_value", - ) - - # Make the request - response = await client.get_message_bus(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetMessageBusRequest, dict]]): - The request object. The request message for the - GetMessageBus method. - name (:class:`str`): - Required. The name of the message bus - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.MessageBus: - MessageBus for the messages flowing - through the system. The admin has - visibility and control over the messages - being published and consumed and can - restrict publishers and subscribers to - only a subset of data available in the - system by defining authorization - policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetMessageBusRequest): - request = eventarc.GetMessageBusRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_message_bus] - - # Certain 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_message_buses(self, - request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessageBusesAsyncPager: - r"""List message buses. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_message_buses(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_buses(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListMessageBusesRequest, dict]]): - The request object. The request message for the - ListMessageBuses method. - parent (:class:`str`): - Required. The parent collection to - list triggers on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesAsyncPager: - The response message for the ListMessageBuses method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListMessageBusesRequest): - request = eventarc.ListMessageBusesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_message_buses] - - # Certain 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.ListMessageBusesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_message_bus_enrollments(self, - request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessageBusEnrollmentsAsyncPager: - r"""List message bus enrollments. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_message_bus_enrollments(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_bus_enrollments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest, dict]]): - The request object. The request message for the - ``ListMessageBusEnrollments`` method. - parent (:class:`str`): - Required. The parent message bus to - list enrollments on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsAsyncPager: - The response message for the ListMessageBusEnrollments - method.\` - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListMessageBusEnrollmentsRequest): - request = eventarc.ListMessageBusEnrollmentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_message_bus_enrollments] - - # Certain 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.ListMessageBusEnrollmentsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_message_bus(self, - request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, - *, - parent: Optional[str] = None, - message_bus: Optional[gce_message_bus.MessageBus] = None, - message_bus_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new MessageBus in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.CreateMessageBusRequest( - parent="parent_value", - message_bus_id="message_bus_id_value", - ) - - # Make the request - operation = client.create_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreateMessageBusRequest, dict]]): - The request object. The request message for the - CreateMessageBus method. - parent (:class:`str`): - Required. The parent collection in - which to add this message bus. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - message_bus (:class:`google.cloud.eventarc_v1.types.MessageBus`): - Required. The message bus to create. - This corresponds to the ``message_bus`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - message_bus_id (:class:`str`): - Required. The user-provided ID to be assigned to the - MessageBus. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) - - This corresponds to the ``message_bus_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has - visibility and control over the messages being - published and consumed and can restrict publishers - and subscribers to only a subset of data available in - the system by defining authorization policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, message_bus, message_bus_id]) - if request is 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, eventarc.CreateMessageBusRequest): - request = eventarc.CreateMessageBusRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if message_bus is not None: - request.message_bus = message_bus - if message_bus_id is not None: - request.message_bus_id = message_bus_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_message_bus] - - # Certain 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, - gce_message_bus.MessageBus, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_message_bus(self, - request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, - *, - message_bus: Optional[gce_message_bus.MessageBus] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update a single message bus. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateMessageBusRequest( - ) - - # Make the request - operation = client.update_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdateMessageBusRequest, dict]]): - The request object. The request message for the - UpdateMessageBus method. - message_bus (:class:`google.cloud.eventarc_v1.types.MessageBus`): - Required. The MessageBus to be - updated. - - This corresponds to the ``message_bus`` 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 fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has - visibility and control over the messages being - published and consumed and can restrict publishers - and subscribers to only a subset of data available in - the system by defining authorization policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([message_bus, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.UpdateMessageBusRequest): - request = eventarc.UpdateMessageBusRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if message_bus is not None: - request.message_bus = message_bus - 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_message_bus] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("message_bus.name", request.message_bus.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, - gce_message_bus.MessageBus, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_message_bus(self, - request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single message bus. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteMessageBusRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeleteMessageBusRequest, dict]]): - The request object. The request message for the - DeleteMessageBus method. - name (:class:`str`): - Required. The name of the MessageBus - to be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (:class:`str`): - Optional. If provided, the MessageBus - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has - visibility and control over the messages being - published and consumed and can restrict publishers - and subscribers to only a subset of data available in - the system by defining authorization policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeleteMessageBusRequest): - request = eventarc.DeleteMessageBusRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_message_bus] - - # Certain 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, - message_bus.MessageBus, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_enrollment(self, - request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> enrollment.Enrollment: - r"""Get a single Enrollment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetEnrollmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_enrollment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetEnrollmentRequest, dict]]): - The request object. The request message for the - GetEnrollment method. - name (:class:`str`): - Required. The name of the Enrollment - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Enrollment: - An enrollment represents a - subscription for messages on a - particular message bus. It defines a - matching criteria for messages on the - bus and the subscriber endpoint where - matched messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetEnrollmentRequest): - request = eventarc.GetEnrollmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_enrollment] - - # Certain 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_enrollments(self, - request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnrollmentsAsyncPager: - r"""List Enrollments. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_enrollments(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_enrollments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListEnrollmentsRequest, dict]]): - The request object. The request message for the - ListEnrollments method. - parent (:class:`str`): - Required. The parent collection to - list triggers on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsAsyncPager: - The response message for the ListEnrollments method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListEnrollmentsRequest): - request = eventarc.ListEnrollmentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_enrollments] - - # Certain 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.ListEnrollmentsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_enrollment(self, - request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - enrollment: Optional[gce_enrollment.Enrollment] = None, - enrollment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new Enrollment in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.CreateEnrollmentRequest( - parent="parent_value", - enrollment=enrollment, - enrollment_id="enrollment_id_value", - ) - - # Make the request - operation = client.create_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreateEnrollmentRequest, dict]]): - The request object. The request message for the - CreateEnrollment method. - parent (:class:`str`): - Required. The parent collection in - which to add this enrollment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - enrollment (:class:`google.cloud.eventarc_v1.types.Enrollment`): - Required. The enrollment to create. - This corresponds to the ``enrollment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - enrollment_id (:class:`str`): - Required. The user-provided ID to be assigned to the - Enrollment. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). - - This corresponds to the ``enrollment_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message - bus. It defines a matching criteria for messages on - the bus and the subscriber endpoint where matched - messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, enrollment, enrollment_id]) - if request is 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, eventarc.CreateEnrollmentRequest): - request = eventarc.CreateEnrollmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if enrollment is not None: - request.enrollment = enrollment - if enrollment_id is not None: - request.enrollment_id = enrollment_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_enrollment] - - # Certain 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, - gce_enrollment.Enrollment, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_enrollment(self, - request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, - *, - enrollment: Optional[gce_enrollment.Enrollment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update a single Enrollment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.UpdateEnrollmentRequest( - enrollment=enrollment, - ) - - # Make the request - operation = client.update_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdateEnrollmentRequest, dict]]): - The request object. The request message for the - UpdateEnrollment method. - enrollment (:class:`google.cloud.eventarc_v1.types.Enrollment`): - Required. The Enrollment to be - updated. - - This corresponds to the ``enrollment`` 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 fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message - bus. It defines a matching criteria for messages on - the bus and the subscriber endpoint where matched - messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([enrollment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.UpdateEnrollmentRequest): - request = eventarc.UpdateEnrollmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if enrollment is not None: - request.enrollment = enrollment - 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_enrollment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("enrollment.name", request.enrollment.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, - gce_enrollment.Enrollment, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_enrollment(self, - request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single Enrollment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteEnrollmentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeleteEnrollmentRequest, dict]]): - The request object. The request message for the - DeleteEnrollment method. - name (:class:`str`): - Required. The name of the Enrollment - to be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (:class:`str`): - Optional. If provided, the Enrollment - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message - bus. It defines a matching criteria for messages on - the bus and the subscriber endpoint where matched - messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeleteEnrollmentRequest): - request = eventarc.DeleteEnrollmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_enrollment] - - # Certain 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, - enrollment.Enrollment, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_pipeline(self, - request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pipeline.Pipeline: - r"""Get a single Pipeline. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetPipelineRequest( - name="name_value", - ) - - # Make the request - response = await client.get_pipeline(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetPipelineRequest, dict]]): - The request object. The request message for the - GetPipeline method. - name (:class:`str`): - Required. The name of the pipeline 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Pipeline: - A representation of the Pipeline - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetPipelineRequest): - request = eventarc.GetPipelineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_pipeline] - - # Certain 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_pipelines(self, - request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPipelinesAsyncPager: - r"""List pipelines. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_pipelines(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListPipelinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_pipelines(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListPipelinesRequest, dict]]): - The request object. The request message for the - ListPipelines method. - parent (:class:`str`): - Required. The parent collection to - list pipelines on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesAsyncPager: - The response message for the - ListPipelines method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListPipelinesRequest): - request = eventarc.ListPipelinesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_pipelines] - - # Certain 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.ListPipelinesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_pipeline(self, - request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, - *, - parent: Optional[str] = None, - pipeline: Optional[gce_pipeline.Pipeline] = None, - pipeline_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new Pipeline in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.CreatePipelineRequest( - parent="parent_value", - pipeline=pipeline, - pipeline_id="pipeline_id_value", - ) - - # Make the request - operation = client.create_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreatePipelineRequest, dict]]): - The request object. The request message for the - CreatePipeline method. - parent (:class:`str`): - Required. The parent collection in - which to add this pipeline. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - pipeline (:class:`google.cloud.eventarc_v1.types.Pipeline`): - Required. The pipeline to create. - This corresponds to the ``pipeline`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - pipeline_id (:class:`str`): - Required. The user-provided ID to be - assigned to the Pipeline. - - This corresponds to the ``pipeline_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Pipeline` A - representation of the Pipeline resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, pipeline, pipeline_id]) - if request is 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, eventarc.CreatePipelineRequest): - request = eventarc.CreatePipelineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if pipeline is not None: - request.pipeline = pipeline - if pipeline_id is not None: - request.pipeline_id = pipeline_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_pipeline] - - # Certain 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, - gce_pipeline.Pipeline, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_pipeline(self, - request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, - *, - pipeline: Optional[gce_pipeline.Pipeline] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update a single pipeline. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.UpdatePipelineRequest( - pipeline=pipeline, - ) - - # Make the request - operation = client.update_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdatePipelineRequest, dict]]): - The request object. The request message for the - UpdatePipeline method. - pipeline (:class:`google.cloud.eventarc_v1.types.Pipeline`): - Required. The Pipeline to be updated. - This corresponds to the ``pipeline`` 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 fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Pipeline` A - representation of the Pipeline resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([pipeline, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.UpdatePipelineRequest): - request = eventarc.UpdatePipelineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if pipeline is not None: - request.pipeline = pipeline - 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_pipeline] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("pipeline.name", request.pipeline.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, - gce_pipeline.Pipeline, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_pipeline(self, - request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single pipeline. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeletePipelineRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeletePipelineRequest, dict]]): - The request object. The request message for the - DeletePipeline method. - name (:class:`str`): - Required. The name of the Pipeline to - be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (:class:`str`): - Optional. If provided, the Pipeline - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Pipeline` A - representation of the Pipeline resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeletePipelineRequest): - request = eventarc.DeletePipelineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_pipeline] - - # Certain 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, - pipeline.Pipeline, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_google_api_source(self, - request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> google_api_source.GoogleApiSource: - r"""Get a single GoogleApiSource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_get_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_google_api_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest, dict]]): - The request object. The request message for the - GetGoogleApiSource method. - name (:class:`str`): - Required. The name of the google api - source 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.GoogleApiSource: - A GoogleApiSource represents a - subscription of 1P events from a - MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetGoogleApiSourceRequest): - request = eventarc.GetGoogleApiSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_google_api_source] - - # Certain 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_google_api_sources(self, - request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListGoogleApiSourcesAsyncPager: - r"""List GoogleApiSources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_list_google_api_sources(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListGoogleApiSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_google_api_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest, dict]]): - The request object. The request message for the - ListGoogleApiSources method. - parent (:class:`str`): - Required. The parent collection to - list GoogleApiSources on. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesAsyncPager: - The response message for the ListGoogleApiSources - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.ListGoogleApiSourcesRequest): - request = eventarc.ListGoogleApiSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_google_api_sources] - - # Certain 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.ListGoogleApiSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_google_api_source(self, - request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - google_api_source_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create a new GoogleApiSource in a particular project - and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_create_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.CreateGoogleApiSourceRequest( - parent="parent_value", - google_api_source=google_api_source, - google_api_source_id="google_api_source_id_value", - ) - - # Make the request - operation = client.create_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest, dict]]): - The request object. The request message for the - CreateGoogleApiSource method. - parent (:class:`str`): - Required. The parent collection in - which to add this google api source. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - google_api_source (:class:`google.cloud.eventarc_v1.types.GoogleApiSource`): - Required. The google api source to - create. - - This corresponds to the ``google_api_source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - google_api_source_id (:class:`str`): - Required. The user-provided ID to be assigned to the - GoogleApiSource. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). - - This corresponds to the ``google_api_source_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.GoogleApiSource` - A GoogleApiSource represents a subscription of 1P events - from a MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, google_api_source, google_api_source_id]) - if request is 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, eventarc.CreateGoogleApiSourceRequest): - request = eventarc.CreateGoogleApiSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if google_api_source is not None: - request.google_api_source = google_api_source - if google_api_source_id is not None: - request.google_api_source_id = google_api_source_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_google_api_source] - - # Certain 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, - gce_google_api_source.GoogleApiSource, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_google_api_source(self, - request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, - *, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update a single GoogleApiSource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_update_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.UpdateGoogleApiSourceRequest( - google_api_source=google_api_source, - ) - - # Make the request - operation = client.update_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest, dict]]): - The request object. The request message for the - UpdateGoogleApiSource method. - google_api_source (:class:`google.cloud.eventarc_v1.types.GoogleApiSource`): - Required. The GoogleApiSource to be - updated. - - This corresponds to the ``google_api_source`` 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 fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.GoogleApiSource` - A GoogleApiSource represents a subscription of 1P events - from a MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([google_api_source, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, eventarc.UpdateGoogleApiSourceRequest): - request = eventarc.UpdateGoogleApiSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if google_api_source is not None: - request.google_api_source = google_api_source - 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_google_api_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_api_source.name", request.google_api_source.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, - gce_google_api_source.GoogleApiSource, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_google_api_source(self, - request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete a single GoogleApiSource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - async def sample_delete_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest, dict]]): - The request object. The request message for the - DeleteGoogleApiSource method. - name (:class:`str`): - Required. The name of the - GoogleApiSource to be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (:class:`str`): - Optional. If provided, the MessageBus - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.GoogleApiSource` - A GoogleApiSource represents a subscription of 1P events - from a MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeleteGoogleApiSourceRequest): - request = eventarc.DeleteGoogleApiSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_google_api_source] - - # Certain 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, - google_api_source.GoogleApiSource, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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) -> "EventarcAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EventarcAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py deleted file mode 100644 index 3149b461d564..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/client.py +++ /dev/null @@ -1,6147 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.eventarc_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.eventarc_v1.services.eventarc import pagers -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel as gce_channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import enrollment as gce_enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import logging_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import message_bus as gce_message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import pipeline as gce_pipeline -from google.cloud.eventarc_v1.types import trigger -from google.cloud.eventarc_v1.types import trigger as gce_trigger -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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EventarcTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EventarcGrpcTransport -from .transports.grpc_asyncio import EventarcGrpcAsyncIOTransport -from .transports.rest import EventarcRestTransport - - -class EventarcClientMeta(type): - """Metaclass for the Eventarc 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[EventarcTransport]] - _transport_registry["grpc"] = EventarcGrpcTransport - _transport_registry["grpc_asyncio"] = EventarcGrpcAsyncIOTransport - _transport_registry["rest"] = EventarcRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EventarcTransport]: - """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 EventarcClient(metaclass=EventarcClientMeta): - """Eventarc allows users to subscribe to various events that are - provided by Google Cloud services and forward them to supported - destinations. - """ - - @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 = "eventarc.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "eventarc.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EventarcClient: 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: - EventarcClient: 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) -> EventarcTransport: - """Returns the transport used by the client instance. - - Returns: - EventarcTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def channel_path(project: str,location: str,channel: str,) -> str: - """Returns a fully-qualified channel string.""" - return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) - - @staticmethod - def parse_channel_path(path: str) -> Dict[str,str]: - """Parses a channel path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def channel_connection_path(project: str,location: str,channel_connection: str,) -> str: - """Returns a fully-qualified channel_connection string.""" - return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) - - @staticmethod - def parse_channel_connection_path(path: str) -> Dict[str,str]: - """Parses a channel_connection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: - """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - - @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: - """Parses a cloud_function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?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 enrollment_path(project: str,location: str,enrollment: str,) -> str: - """Returns a fully-qualified enrollment string.""" - return "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) - - @staticmethod - def parse_enrollment_path(path: str) -> Dict[str,str]: - """Parses a enrollment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def google_api_source_path(project: str,location: str,google_api_source: str,) -> str: - """Returns a fully-qualified google_api_source string.""" - return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) - - @staticmethod - def parse_google_api_source_path(path: str) -> Dict[str,str]: - """Parses a google_api_source path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def google_channel_config_path(project: str,location: str,) -> str: - """Returns a fully-qualified google_channel_config string.""" - return "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) - - @staticmethod - def parse_google_channel_config_path(path: str) -> Dict[str,str]: - """Parses a google_channel_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def message_bus_path(project: str,location: str,message_bus: str,) -> str: - """Returns a fully-qualified message_bus string.""" - return "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) - - @staticmethod - def parse_message_bus_path(path: str) -> Dict[str,str]: - """Parses a message_bus path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def network_attachment_path(project: str,region: str,networkattachment: str,) -> str: - """Returns a fully-qualified network_attachment string.""" - return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) - - @staticmethod - def parse_network_attachment_path(path: str) -> Dict[str,str]: - """Parses a network_attachment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def pipeline_path(project: str,location: str,pipeline: str,) -> str: - """Returns a fully-qualified pipeline string.""" - return "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) - - @staticmethod - def parse_pipeline_path(path: str) -> Dict[str,str]: - """Parses a pipeline path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def provider_path(project: str,location: str,provider: str,) -> str: - """Returns a fully-qualified provider string.""" - return "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) - - @staticmethod - def parse_provider_path(path: str) -> Dict[str,str]: - """Parses a provider path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path() -> str: - """Returns a fully-qualified service string.""" - return "*".format() - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^.*$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_account_path(project: str,service_account: str,) -> str: - """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) - - @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: - """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def trigger_path(project: str,location: str,trigger: str,) -> str: - """Returns a fully-qualified trigger string.""" - return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) - - @staticmethod - def parse_trigger_path(path: str) -> Dict[str,str]: - """Parses a trigger path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: - """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - - @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: - """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", 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 = EventarcClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EventarcClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EventarcClient._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 = EventarcClient._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 - - @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, EventarcTransport, Callable[..., EventarcTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the eventarc client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. 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,EventarcTransport,Callable[..., EventarcTransport]]]): - 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 EventarcTransport 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 = EventarcClient._read_environment_variables() - self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EventarcClient._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 - - 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, EventarcTransport) - if transport_provided: - # transport is a EventarcTransport 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(EventarcTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EventarcClient._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[EventarcTransport], Callable[..., EventarcTransport]] = ( - EventarcClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EventarcTransport], 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, - ) - - def get_trigger(self, - request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trigger.Trigger: - r"""Get a single trigger. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetTriggerRequest( - name="name_value", - ) - - # Make the request - response = client.get_trigger(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetTriggerRequest, dict]): - The request object. The request message for the - GetTrigger method. - name (str): - Required. The name of the trigger 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Trigger: - A representation of the trigger - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetTriggerRequest): - request = eventarc.GetTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_trigger] - - # Certain 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_triggers(self, - request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTriggersPager: - r"""List triggers. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_triggers(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListTriggersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_triggers(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListTriggersRequest, dict]): - The request object. The request message for the - ListTriggers method. - parent (str): - Required. The parent collection to - list triggers on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersPager: - The response message for the ListTriggers method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListTriggersRequest): - request = eventarc.ListTriggersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_triggers] - - # Certain 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.ListTriggersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_trigger(self, - request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, - *, - parent: Optional[str] = None, - trigger: Optional[gce_trigger.Trigger] = None, - trigger_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new trigger in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - trigger = eventarc_v1.Trigger() - trigger.name = "name_value" - trigger.event_filters.attribute = "attribute_value" - trigger.event_filters.value = "value_value" - trigger.destination.cloud_run.service = "service_value" - trigger.destination.cloud_run.region = "region_value" - - request = eventarc_v1.CreateTriggerRequest( - parent="parent_value", - trigger=trigger, - trigger_id="trigger_id_value", - ) - - # Make the request - operation = client.create_trigger(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreateTriggerRequest, dict]): - The request object. The request message for the - CreateTrigger method. - parent (str): - Required. The parent collection in - which to add this trigger. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger (google.cloud.eventarc_v1.types.Trigger): - Required. The trigger to create. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - trigger_id (str): - Required. The user-provided ID to be - assigned to the trigger. - - This corresponds to the ``trigger_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Trigger` A - representation of the trigger resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, trigger, trigger_id]) - if request is 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, eventarc.CreateTriggerRequest): - request = eventarc.CreateTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if trigger is not None: - request.trigger = trigger - if trigger_id is not None: - request.trigger_id = trigger_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_trigger] - - # Certain 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, - gce_trigger.Trigger, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_trigger(self, - request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, - *, - trigger: Optional[gce_trigger.Trigger] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update a single trigger. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateTriggerRequest( - ) - - # Make the request - operation = client.update_trigger(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdateTriggerRequest, dict]): - The request object. The request message for the - UpdateTrigger method. - trigger (google.cloud.eventarc_v1.types.Trigger): - The trigger to be updated. - This corresponds to the ``trigger`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update - all fields, provide a field mask of "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - allow_missing (bool): - If set to true, and the trigger is not found, a new - trigger will be created. In this situation, - ``update_mask`` is ignored. - - This corresponds to the ``allow_missing`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Trigger` A - representation of the trigger resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([trigger, update_mask, allow_missing]) - if request is 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, eventarc.UpdateTriggerRequest): - request = eventarc.UpdateTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if trigger is not None: - request.trigger = trigger - if update_mask is not None: - request.update_mask = update_mask - if allow_missing is not None: - request.allow_missing = allow_missing - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_trigger] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("trigger.name", request.trigger.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, - gce_trigger.Trigger, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_trigger(self, - request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single trigger. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteTriggerRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_trigger(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeleteTriggerRequest, dict]): - The request object. The request message for the - DeleteTrigger method. - name (str): - Required. The name of the trigger to - be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - allow_missing (bool): - If set to true, and the trigger is - not found, the request will succeed but - no action will be taken on the server. - - This corresponds to the ``allow_missing`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Trigger` A - representation of the trigger resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, allow_missing]) - if request is 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, eventarc.DeleteTriggerRequest): - request = eventarc.DeleteTriggerRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if allow_missing is not None: - request.allow_missing = allow_missing - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_trigger] - - # Certain 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, - trigger.Trigger, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_channel(self, - request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> channel.Channel: - r"""Get a single Channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelRequest( - name="name_value", - ) - - # Make the request - response = client.get_channel(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetChannelRequest, dict]): - The request object. The request message for the - GetChannel method. - name (str): - Required. The name of the channel 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Channel: - A representation of the Channel - resource. A Channel is a resource on - which event providers publish their - events. The published events are - delivered through the transport - associated with the channel. Note that a - channel is associated with exactly one - event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetChannelRequest): - request = eventarc.GetChannelRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_channel] - - # Certain 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_channels(self, - request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListChannelsPager: - r"""List channels. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_channels(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channels(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListChannelsRequest, dict]): - The request object. The request message for the - ListChannels method. - parent (str): - Required. The parent collection to - list channels on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsPager: - The response message for the ListChannels method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListChannelsRequest): - request = eventarc.ListChannelsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_channels] - - # Certain 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.ListChannelsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_channel(self, - request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel: Optional[gce_channel.Channel] = None, - channel_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new channel in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - channel = eventarc_v1.Channel() - channel.pubsub_topic = "pubsub_topic_value" - channel.name = "name_value" - - request = eventarc_v1.CreateChannelRequest( - parent="parent_value", - channel=channel, - channel_id="channel_id_value", - ) - - # Make the request - operation = client.create_channel(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreateChannelRequest, dict]): - The request object. The request message for the - CreateChannel method. - parent (str): - Required. The parent collection in - which to add this channel. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel (google.cloud.eventarc_v1.types.Channel): - Required. The channel to create. - This corresponds to the ``channel`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel_id (str): - Required. The user-provided ID to be - assigned to the channel. - - This corresponds to the ``channel_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. - A Channel is a resource on which event providers - publish their events. The published events are - delivered through the transport associated with the - channel. Note that a channel is associated with - exactly one event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, channel, channel_id]) - if request is 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, eventarc.CreateChannelRequest): - request = eventarc.CreateChannelRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if channel is not None: - request.channel = channel - if channel_id is not None: - request.channel_id = channel_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_channel_] - - # Certain 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, - gce_channel.Channel, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_channel(self, - request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, - *, - channel: Optional[gce_channel.Channel] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update a single channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateChannelRequest( - ) - - # Make the request - operation = client.update_channel(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdateChannelRequest, dict]): - The request object. The request message for the - UpdateChannel method. - channel (google.cloud.eventarc_v1.types.Channel): - The channel to be updated. - This corresponds to the ``channel`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update - all fields, provide a field mask of "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. - A Channel is a resource on which event providers - publish their events. The published events are - delivered through the transport associated with the - channel. Note that a channel is associated with - exactly one event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([channel, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.UpdateChannelRequest): - request = eventarc.UpdateChannelRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if channel is not None: - request.channel = channel - 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_channel] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("channel.name", request.channel.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, - gce_channel.Channel, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_channel(self, - request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeleteChannelRequest, dict]): - The request object. The request message for the - DeleteChannel method. - name (str): - Required. The name of the channel to - be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Channel` A representation of the Channel resource. - A Channel is a resource on which event providers - publish their events. The published events are - delivered through the transport associated with the - channel. Note that a channel is associated with - exactly one event provider. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.DeleteChannelRequest): - request = eventarc.DeleteChannelRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_channel] - - # Certain 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, - channel.Channel, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_provider(self, - request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> discovery.Provider: - r"""Get a single Provider. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_provider(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetProviderRequest( - name="name_value", - ) - - # Make the request - response = client.get_provider(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetProviderRequest, dict]): - The request object. The request message for the - GetProvider method. - name (str): - Required. The name of the provider 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Provider: - A representation of the Provider - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetProviderRequest): - request = eventarc.GetProviderRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_provider] - - # Certain 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_providers(self, - request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListProvidersPager: - r"""List providers. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_providers(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_providers(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListProvidersRequest, dict]): - The request object. The request message for the - ListProviders method. - parent (str): - Required. The parent of the provider - to get. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersPager: - The response message for the ListProviders method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListProvidersRequest): - request = eventarc.ListProvidersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_providers] - - # Certain 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.ListProvidersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_channel_connection(self, - request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> channel_connection.ChannelConnection: - r"""Get a single ChannelConnection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_channel_connection(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelConnectionRequest( - name="name_value", - ) - - # Make the request - response = client.get_channel_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetChannelConnectionRequest, dict]): - The request object. The request message for the - GetChannelConnection method. - name (str): - Required. The name of the channel - connection 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.ChannelConnection: - A representation of the - ChannelConnection resource. A - ChannelConnection is a resource which - event providers create during the - activation process to establish a - connection between the provider and the - subscriber channel. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetChannelConnectionRequest): - request = eventarc.GetChannelConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_channel_connection] - - # Certain 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_channel_connections(self, - request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListChannelConnectionsPager: - r"""List channel connections. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_channel_connections(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channel_connections(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListChannelConnectionsRequest, dict]): - The request object. The request message for the - ListChannelConnections method. - parent (str): - Required. The parent collection from - which to list channel connections. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsPager: - The response message for the ListChannelConnections - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListChannelConnectionsRequest): - request = eventarc.ListChannelConnectionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_channel_connections] - - # Certain 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.ListChannelConnectionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_channel_connection(self, - request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, - channel_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new ChannelConnection in a particular - project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_channel_connection(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - channel_connection = eventarc_v1.ChannelConnection() - channel_connection.name = "name_value" - channel_connection.channel = "channel_value" - - request = eventarc_v1.CreateChannelConnectionRequest( - parent="parent_value", - channel_connection=channel_connection, - channel_connection_id="channel_connection_id_value", - ) - - # Make the request - operation = client.create_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreateChannelConnectionRequest, dict]): - The request object. The request message for the - CreateChannelConnection method. - parent (str): - Required. The parent collection in - which to add this channel connection. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel_connection (google.cloud.eventarc_v1.types.ChannelConnection): - Required. Channel connection to - create. - - This corresponds to the ``channel_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - channel_connection_id (str): - Required. The user-provided ID to be - assigned to the channel connection. - - This corresponds to the ``channel_connection_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. - A ChannelConnection is a resource which event - providers create during the activation process to - establish a connection between the provider and the - subscriber channel. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, channel_connection, channel_connection_id]) - if request is 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, eventarc.CreateChannelConnectionRequest): - request = eventarc.CreateChannelConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if channel_connection is not None: - request.channel_connection = channel_connection - if channel_connection_id is not None: - request.channel_connection_id = channel_connection_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_channel_connection] - - # Certain 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, - gce_channel_connection.ChannelConnection, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_channel_connection(self, - request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single ChannelConnection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_channel_connection(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest, dict]): - The request object. The request message for the - DeleteChannelConnection method. - name (str): - Required. The name of the channel - connection 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.ChannelConnection` A representation of the ChannelConnection resource. - A ChannelConnection is a resource which event - providers create during the activation process to - establish a connection between the provider and the - subscriber channel. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.DeleteChannelConnectionRequest): - request = eventarc.DeleteChannelConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_channel_connection] - - # Certain 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, - channel_connection.ChannelConnection, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_google_channel_config(self, - request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> google_channel_config.GoogleChannelConfig: - r"""Get a GoogleChannelConfig - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleChannelConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_google_channel_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest, dict]): - The request object. The request message for the - GetGoogleChannelConfig method. - name (str): - Required. The name of the config 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetGoogleChannelConfigRequest): - request = eventarc.GetGoogleChannelConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_google_channel_config] - - # Certain 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_google_channel_config(self, - request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, - *, - google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: - r"""Update a single GoogleChannelConfig - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - google_channel_config = eventarc_v1.GoogleChannelConfig() - google_channel_config.name = "name_value" - - request = eventarc_v1.UpdateGoogleChannelConfigRequest( - google_channel_config=google_channel_config, - ) - - # Make the request - response = client.update_google_channel_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest, dict]): - The request object. The request message for the - UpdateGoogleChannelConfig method. - google_channel_config (google.cloud.eventarc_v1.types.GoogleChannelConfig): - Required. The config to be updated. - This corresponds to the ``google_channel_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update - all fields, provide a field mask of "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([google_channel_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.UpdateGoogleChannelConfigRequest): - request = eventarc.UpdateGoogleChannelConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if google_channel_config is not None: - request.google_channel_config = google_channel_config - 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_google_channel_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_channel_config.name", request.google_channel_config.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 get_message_bus(self, - request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> message_bus.MessageBus: - r"""Get a single MessageBus. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetMessageBusRequest( - name="name_value", - ) - - # Make the request - response = client.get_message_bus(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetMessageBusRequest, dict]): - The request object. The request message for the - GetMessageBus method. - name (str): - Required. The name of the message bus - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.MessageBus: - MessageBus for the messages flowing - through the system. The admin has - visibility and control over the messages - being published and consumed and can - restrict publishers and subscribers to - only a subset of data available in the - system by defining authorization - policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetMessageBusRequest): - request = eventarc.GetMessageBusRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_message_bus] - - # Certain 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_message_buses(self, - request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessageBusesPager: - r"""List message buses. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_message_buses(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_buses(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListMessageBusesRequest, dict]): - The request object. The request message for the - ListMessageBuses method. - parent (str): - Required. The parent collection to - list triggers on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesPager: - The response message for the ListMessageBuses method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListMessageBusesRequest): - request = eventarc.ListMessageBusesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_message_buses] - - # Certain 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.ListMessageBusesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_message_bus_enrollments(self, - request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessageBusEnrollmentsPager: - r"""List message bus enrollments. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_message_bus_enrollments(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_bus_enrollments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest, dict]): - The request object. The request message for the - ``ListMessageBusEnrollments`` method. - parent (str): - Required. The parent message bus to - list enrollments on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsPager: - The response message for the ListMessageBusEnrollments - method.\` - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListMessageBusEnrollmentsRequest): - request = eventarc.ListMessageBusEnrollmentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_message_bus_enrollments] - - # Certain 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.ListMessageBusEnrollmentsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_message_bus(self, - request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, - *, - parent: Optional[str] = None, - message_bus: Optional[gce_message_bus.MessageBus] = None, - message_bus_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new MessageBus in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.CreateMessageBusRequest( - parent="parent_value", - message_bus_id="message_bus_id_value", - ) - - # Make the request - operation = client.create_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreateMessageBusRequest, dict]): - The request object. The request message for the - CreateMessageBus method. - parent (str): - Required. The parent collection in - which to add this message bus. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - message_bus (google.cloud.eventarc_v1.types.MessageBus): - Required. The message bus to create. - This corresponds to the ``message_bus`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - message_bus_id (str): - Required. The user-provided ID to be assigned to the - MessageBus. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) - - This corresponds to the ``message_bus_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has - visibility and control over the messages being - published and consumed and can restrict publishers - and subscribers to only a subset of data available in - the system by defining authorization policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, message_bus, message_bus_id]) - if request is 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, eventarc.CreateMessageBusRequest): - request = eventarc.CreateMessageBusRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if message_bus is not None: - request.message_bus = message_bus - if message_bus_id is not None: - request.message_bus_id = message_bus_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_message_bus] - - # Certain 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, - gce_message_bus.MessageBus, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_message_bus(self, - request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, - *, - message_bus: Optional[gce_message_bus.MessageBus] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update a single message bus. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateMessageBusRequest( - ) - - # Make the request - operation = client.update_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdateMessageBusRequest, dict]): - The request object. The request message for the - UpdateMessageBus method. - message_bus (google.cloud.eventarc_v1.types.MessageBus): - Required. The MessageBus to be - updated. - - This corresponds to the ``message_bus`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has - visibility and control over the messages being - published and consumed and can restrict publishers - and subscribers to only a subset of data available in - the system by defining authorization policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([message_bus, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.UpdateMessageBusRequest): - request = eventarc.UpdateMessageBusRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if message_bus is not None: - request.message_bus = message_bus - 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_message_bus] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("message_bus.name", request.message_bus.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, - gce_message_bus.MessageBus, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_message_bus(self, - request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single message bus. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteMessageBusRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeleteMessageBusRequest, dict]): - The request object. The request message for the - DeleteMessageBus method. - name (str): - Required. The name of the MessageBus - to be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (str): - Optional. If provided, the MessageBus - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has - visibility and control over the messages being - published and consumed and can restrict publishers - and subscribers to only a subset of data available in - the system by defining authorization policies. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeleteMessageBusRequest): - request = eventarc.DeleteMessageBusRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_message_bus] - - # Certain 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, - message_bus.MessageBus, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_enrollment(self, - request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> enrollment.Enrollment: - r"""Get a single Enrollment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetEnrollmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_enrollment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetEnrollmentRequest, dict]): - The request object. The request message for the - GetEnrollment method. - name (str): - Required. The name of the Enrollment - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Enrollment: - An enrollment represents a - subscription for messages on a - particular message bus. It defines a - matching criteria for messages on the - bus and the subscriber endpoint where - matched messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetEnrollmentRequest): - request = eventarc.GetEnrollmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_enrollment] - - # Certain 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_enrollments(self, - request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnrollmentsPager: - r"""List Enrollments. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_enrollments(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_enrollments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListEnrollmentsRequest, dict]): - The request object. The request message for the - ListEnrollments method. - parent (str): - Required. The parent collection to - list triggers on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsPager: - The response message for the ListEnrollments method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListEnrollmentsRequest): - request = eventarc.ListEnrollmentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_enrollments] - - # Certain 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.ListEnrollmentsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_enrollment(self, - request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - enrollment: Optional[gce_enrollment.Enrollment] = None, - enrollment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new Enrollment in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.CreateEnrollmentRequest( - parent="parent_value", - enrollment=enrollment, - enrollment_id="enrollment_id_value", - ) - - # Make the request - operation = client.create_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreateEnrollmentRequest, dict]): - The request object. The request message for the - CreateEnrollment method. - parent (str): - Required. The parent collection in - which to add this enrollment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - enrollment (google.cloud.eventarc_v1.types.Enrollment): - Required. The enrollment to create. - This corresponds to the ``enrollment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - enrollment_id (str): - Required. The user-provided ID to be assigned to the - Enrollment. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). - - This corresponds to the ``enrollment_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message - bus. It defines a matching criteria for messages on - the bus and the subscriber endpoint where matched - messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, enrollment, enrollment_id]) - if request is 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, eventarc.CreateEnrollmentRequest): - request = eventarc.CreateEnrollmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if enrollment is not None: - request.enrollment = enrollment - if enrollment_id is not None: - request.enrollment_id = enrollment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_enrollment] - - # Certain 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, - gce_enrollment.Enrollment, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_enrollment(self, - request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, - *, - enrollment: Optional[gce_enrollment.Enrollment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update a single Enrollment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.UpdateEnrollmentRequest( - enrollment=enrollment, - ) - - # Make the request - operation = client.update_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdateEnrollmentRequest, dict]): - The request object. The request message for the - UpdateEnrollment method. - enrollment (google.cloud.eventarc_v1.types.Enrollment): - Required. The Enrollment to be - updated. - - This corresponds to the ``enrollment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message - bus. It defines a matching criteria for messages on - the bus and the subscriber endpoint where matched - messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([enrollment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.UpdateEnrollmentRequest): - request = eventarc.UpdateEnrollmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if enrollment is not None: - request.enrollment = enrollment - 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_enrollment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("enrollment.name", request.enrollment.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, - gce_enrollment.Enrollment, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_enrollment(self, - request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single Enrollment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteEnrollmentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeleteEnrollmentRequest, dict]): - The request object. The request message for the - DeleteEnrollment method. - name (str): - Required. The name of the Enrollment - to be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (str): - Optional. If provided, the Enrollment - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message - bus. It defines a matching criteria for messages on - the bus and the subscriber endpoint where matched - messages should be delivered. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeleteEnrollmentRequest): - request = eventarc.DeleteEnrollmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_enrollment] - - # Certain 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, - enrollment.Enrollment, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_pipeline(self, - request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pipeline.Pipeline: - r"""Get a single Pipeline. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetPipelineRequest( - name="name_value", - ) - - # Make the request - response = client.get_pipeline(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetPipelineRequest, dict]): - The request object. The request message for the - GetPipeline method. - name (str): - Required. The name of the pipeline 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.Pipeline: - A representation of the Pipeline - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetPipelineRequest): - request = eventarc.GetPipelineRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_pipeline] - - # Certain 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_pipelines(self, - request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPipelinesPager: - r"""List pipelines. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_pipelines(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListPipelinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_pipelines(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListPipelinesRequest, dict]): - The request object. The request message for the - ListPipelines method. - parent (str): - Required. The parent collection to - list pipelines on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesPager: - The response message for the - ListPipelines method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListPipelinesRequest): - request = eventarc.ListPipelinesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_pipelines] - - # Certain 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.ListPipelinesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_pipeline(self, - request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, - *, - parent: Optional[str] = None, - pipeline: Optional[gce_pipeline.Pipeline] = None, - pipeline_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new Pipeline in a particular project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.CreatePipelineRequest( - parent="parent_value", - pipeline=pipeline, - pipeline_id="pipeline_id_value", - ) - - # Make the request - operation = client.create_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreatePipelineRequest, dict]): - The request object. The request message for the - CreatePipeline method. - parent (str): - Required. The parent collection in - which to add this pipeline. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - pipeline (google.cloud.eventarc_v1.types.Pipeline): - Required. The pipeline to create. - This corresponds to the ``pipeline`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - pipeline_id (str): - Required. The user-provided ID to be - assigned to the Pipeline. - - This corresponds to the ``pipeline_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Pipeline` A - representation of the Pipeline resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, pipeline, pipeline_id]) - if request is 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, eventarc.CreatePipelineRequest): - request = eventarc.CreatePipelineRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if pipeline is not None: - request.pipeline = pipeline - if pipeline_id is not None: - request.pipeline_id = pipeline_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_pipeline] - - # Certain 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, - gce_pipeline.Pipeline, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_pipeline(self, - request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, - *, - pipeline: Optional[gce_pipeline.Pipeline] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update a single pipeline. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.UpdatePipelineRequest( - pipeline=pipeline, - ) - - # Make the request - operation = client.update_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdatePipelineRequest, dict]): - The request object. The request message for the - UpdatePipeline method. - pipeline (google.cloud.eventarc_v1.types.Pipeline): - Required. The Pipeline to be updated. - This corresponds to the ``pipeline`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Pipeline` A - representation of the Pipeline resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([pipeline, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.UpdatePipelineRequest): - request = eventarc.UpdatePipelineRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if pipeline is not None: - request.pipeline = pipeline - 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_pipeline] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("pipeline.name", request.pipeline.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, - gce_pipeline.Pipeline, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_pipeline(self, - request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single pipeline. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeletePipelineRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeletePipelineRequest, dict]): - The request object. The request message for the - DeletePipeline method. - name (str): - Required. The name of the Pipeline to - be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (str): - Optional. If provided, the Pipeline - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.Pipeline` A - representation of the Pipeline resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeletePipelineRequest): - request = eventarc.DeletePipelineRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_pipeline] - - # Certain 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, - pipeline.Pipeline, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_google_api_source(self, - request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> google_api_source.GoogleApiSource: - r"""Get a single GoogleApiSource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_get_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_google_api_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest, dict]): - The request object. The request message for the - GetGoogleApiSource method. - name (str): - Required. The name of the google api - source 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.types.GoogleApiSource: - A GoogleApiSource represents a - subscription of 1P events from a - MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is 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, eventarc.GetGoogleApiSourceRequest): - request = eventarc.GetGoogleApiSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_google_api_source] - - # Certain 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_google_api_sources(self, - request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListGoogleApiSourcesPager: - r"""List GoogleApiSources. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_list_google_api_sources(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListGoogleApiSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_google_api_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest, dict]): - The request object. The request message for the - ListGoogleApiSources method. - parent (str): - Required. The parent collection to - list GoogleApiSources on. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesPager: - The response message for the ListGoogleApiSources - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.ListGoogleApiSourcesRequest): - request = eventarc.ListGoogleApiSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_google_api_sources] - - # Certain 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.ListGoogleApiSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_google_api_source(self, - request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - google_api_source_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create a new GoogleApiSource in a particular project - and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_create_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.CreateGoogleApiSourceRequest( - parent="parent_value", - google_api_source=google_api_source, - google_api_source_id="google_api_source_id_value", - ) - - # Make the request - operation = client.create_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest, dict]): - The request object. The request message for the - CreateGoogleApiSource method. - parent (str): - Required. The parent collection in - which to add this google api source. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): - Required. The google api source to - create. - - This corresponds to the ``google_api_source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - google_api_source_id (str): - Required. The user-provided ID to be assigned to the - GoogleApiSource. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). - - This corresponds to the ``google_api_source_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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.GoogleApiSource` - A GoogleApiSource represents a subscription of 1P events - from a MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, google_api_source, google_api_source_id]) - if request is 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, eventarc.CreateGoogleApiSourceRequest): - request = eventarc.CreateGoogleApiSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if google_api_source is not None: - request.google_api_source = google_api_source - if google_api_source_id is not None: - request.google_api_source_id = google_api_source_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_google_api_source] - - # Certain 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, - gce_google_api_source.GoogleApiSource, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_google_api_source(self, - request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, - *, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update a single GoogleApiSource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_update_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.UpdateGoogleApiSourceRequest( - google_api_source=google_api_source, - ) - - # Make the request - operation = client.update_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest, dict]): - The request object. The request message for the - UpdateGoogleApiSource method. - google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): - Required. The GoogleApiSource to be - updated. - - This corresponds to the ``google_api_source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields - explicitly provided are updated. If no field mask is - provided, all provided fields in the request are - updated. To update all fields, provide a field mask of - "*". - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.GoogleApiSource` - A GoogleApiSource represents a subscription of 1P events - from a MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([google_api_source, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, eventarc.UpdateGoogleApiSourceRequest): - request = eventarc.UpdateGoogleApiSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if google_api_source is not None: - request.google_api_source = google_api_source - 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_google_api_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_api_source.name", request.google_api_source.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, - gce_google_api_source.GoogleApiSource, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_google_api_source(self, - request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete a single GoogleApiSource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import eventarc_v1 - - def sample_delete_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest, dict]): - The request object. The request message for the - DeleteGoogleApiSource method. - name (str): - Required. The name of the - GoogleApiSource to be deleted. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - etag (str): - Optional. If provided, the MessageBus - will only be deleted if the etag matches - the current etag on the resource. - - This corresponds to the ``etag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.eventarc_v1.types.GoogleApiSource` - A GoogleApiSource represents a subscription of 1P events - from a MessageBus. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, etag]) - if request is 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, eventarc.DeleteGoogleApiSourceRequest): - request = eventarc.DeleteGoogleApiSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if etag is not None: - request.etag = etag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_google_api_source] - - # Certain 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, - google_api_source.GoogleApiSource, - metadata_type=eventarc.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "EventarcClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EventarcClient", -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py deleted file mode 100644 index 3e7b93bf7b7e..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/pagers.py +++ /dev/null @@ -1,1250 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -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.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger - - -class ListTriggersPager: - """A pager for iterating through ``list_triggers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``triggers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTriggers`` requests and continue to iterate - through the ``triggers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListTriggersResponse], - request: eventarc.ListTriggersRequest, - response: eventarc.ListTriggersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListTriggersRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListTriggersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListTriggersRequest(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[eventarc.ListTriggersResponse]: - 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[trigger.Trigger]: - for page in self.pages: - yield from page.triggers - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTriggersAsyncPager: - """A pager for iterating through ``list_triggers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``triggers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTriggers`` requests and continue to iterate - through the ``triggers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListTriggersResponse` - attributes are available on the 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[eventarc.ListTriggersResponse]], - request: eventarc.ListTriggersRequest, - response: eventarc.ListTriggersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListTriggersRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListTriggersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListTriggersRequest(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[eventarc.ListTriggersResponse]: - 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[trigger.Trigger]: - async def async_generator(): - async for page in self.pages: - for response in page.triggers: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListChannelsPager: - """A pager for iterating through ``list_channels`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``channels`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListChannels`` requests and continue to iterate - through the ``channels`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListChannelsResponse], - request: eventarc.ListChannelsRequest, - response: eventarc.ListChannelsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListChannelsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListChannelsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListChannelsRequest(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[eventarc.ListChannelsResponse]: - 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[channel.Channel]: - for page in self.pages: - yield from page.channels - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListChannelsAsyncPager: - """A pager for iterating through ``list_channels`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``channels`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListChannels`` requests and continue to iterate - through the ``channels`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListChannelsResponse` - attributes are available on the 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[eventarc.ListChannelsResponse]], - request: eventarc.ListChannelsRequest, - response: eventarc.ListChannelsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListChannelsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListChannelsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListChannelsRequest(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[eventarc.ListChannelsResponse]: - 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[channel.Channel]: - async def async_generator(): - async for page in self.pages: - for response in page.channels: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProvidersPager: - """A pager for iterating through ``list_providers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``providers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProviders`` requests and continue to iterate - through the ``providers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListProvidersResponse], - request: eventarc.ListProvidersRequest, - response: eventarc.ListProvidersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListProvidersRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListProvidersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListProvidersRequest(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[eventarc.ListProvidersResponse]: - 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[discovery.Provider]: - for page in self.pages: - yield from page.providers - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProvidersAsyncPager: - """A pager for iterating through ``list_providers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``providers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProviders`` requests and continue to iterate - through the ``providers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListProvidersResponse` - attributes are available on the 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[eventarc.ListProvidersResponse]], - request: eventarc.ListProvidersRequest, - response: eventarc.ListProvidersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListProvidersRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListProvidersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListProvidersRequest(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[eventarc.ListProvidersResponse]: - 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[discovery.Provider]: - async def async_generator(): - async for page in self.pages: - for response in page.providers: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListChannelConnectionsPager: - """A pager for iterating through ``list_channel_connections`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``channel_connections`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListChannelConnections`` requests and continue to iterate - through the ``channel_connections`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListChannelConnectionsResponse], - request: eventarc.ListChannelConnectionsRequest, - response: eventarc.ListChannelConnectionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListChannelConnectionsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListChannelConnectionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListChannelConnectionsRequest(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[eventarc.ListChannelConnectionsResponse]: - 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[channel_connection.ChannelConnection]: - for page in self.pages: - yield from page.channel_connections - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListChannelConnectionsAsyncPager: - """A pager for iterating through ``list_channel_connections`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``channel_connections`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListChannelConnections`` requests and continue to iterate - through the ``channel_connections`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListChannelConnectionsResponse` - attributes are available on the 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[eventarc.ListChannelConnectionsResponse]], - request: eventarc.ListChannelConnectionsRequest, - response: eventarc.ListChannelConnectionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListChannelConnectionsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListChannelConnectionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListChannelConnectionsRequest(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[eventarc.ListChannelConnectionsResponse]: - 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[channel_connection.ChannelConnection]: - async def async_generator(): - async for page in self.pages: - for response in page.channel_connections: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessageBusesPager: - """A pager for iterating through ``list_message_buses`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``message_buses`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMessageBuses`` requests and continue to iterate - through the ``message_buses`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListMessageBusesResponse], - request: eventarc.ListMessageBusesRequest, - response: eventarc.ListMessageBusesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListMessageBusesRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListMessageBusesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListMessageBusesRequest(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[eventarc.ListMessageBusesResponse]: - 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[message_bus.MessageBus]: - for page in self.pages: - yield from page.message_buses - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessageBusesAsyncPager: - """A pager for iterating through ``list_message_buses`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``message_buses`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMessageBuses`` requests and continue to iterate - through the ``message_buses`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` - attributes are available on the 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[eventarc.ListMessageBusesResponse]], - request: eventarc.ListMessageBusesRequest, - response: eventarc.ListMessageBusesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListMessageBusesRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListMessageBusesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListMessageBusesRequest(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[eventarc.ListMessageBusesResponse]: - 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[message_bus.MessageBus]: - async def async_generator(): - async for page in self.pages: - for response in page.message_buses: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessageBusEnrollmentsPager: - """A pager for iterating through ``list_message_bus_enrollments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``enrollments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMessageBusEnrollments`` requests and continue to iterate - through the ``enrollments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListMessageBusEnrollmentsResponse], - request: eventarc.ListMessageBusEnrollmentsRequest, - response: eventarc.ListMessageBusEnrollmentsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListMessageBusEnrollmentsRequest(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[eventarc.ListMessageBusEnrollmentsResponse]: - 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[str]: - for page in self.pages: - yield from page.enrollments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessageBusEnrollmentsAsyncPager: - """A pager for iterating through ``list_message_bus_enrollments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``enrollments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMessageBusEnrollments`` requests and continue to iterate - through the ``enrollments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` - attributes are available on the 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[eventarc.ListMessageBusEnrollmentsResponse]], - request: eventarc.ListMessageBusEnrollmentsRequest, - response: eventarc.ListMessageBusEnrollmentsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListMessageBusEnrollmentsRequest(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[eventarc.ListMessageBusEnrollmentsResponse]: - 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[str]: - async def async_generator(): - async for page in self.pages: - for response in page.enrollments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEnrollmentsPager: - """A pager for iterating through ``list_enrollments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``enrollments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEnrollments`` requests and continue to iterate - through the ``enrollments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListEnrollmentsResponse], - request: eventarc.ListEnrollmentsRequest, - response: eventarc.ListEnrollmentsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListEnrollmentsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListEnrollmentsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListEnrollmentsRequest(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[eventarc.ListEnrollmentsResponse]: - 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[enrollment.Enrollment]: - for page in self.pages: - yield from page.enrollments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEnrollmentsAsyncPager: - """A pager for iterating through ``list_enrollments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``enrollments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEnrollments`` requests and continue to iterate - through the ``enrollments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` - attributes are available on the 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[eventarc.ListEnrollmentsResponse]], - request: eventarc.ListEnrollmentsRequest, - response: eventarc.ListEnrollmentsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListEnrollmentsRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListEnrollmentsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListEnrollmentsRequest(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[eventarc.ListEnrollmentsResponse]: - 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[enrollment.Enrollment]: - async def async_generator(): - async for page in self.pages: - for response in page.enrollments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPipelinesPager: - """A pager for iterating through ``list_pipelines`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``pipelines`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPipelines`` requests and continue to iterate - through the ``pipelines`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListPipelinesResponse], - request: eventarc.ListPipelinesRequest, - response: eventarc.ListPipelinesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListPipelinesRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListPipelinesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListPipelinesRequest(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[eventarc.ListPipelinesResponse]: - 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[pipeline.Pipeline]: - for page in self.pages: - yield from page.pipelines - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPipelinesAsyncPager: - """A pager for iterating through ``list_pipelines`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``pipelines`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPipelines`` requests and continue to iterate - through the ``pipelines`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` - attributes are available on the 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[eventarc.ListPipelinesResponse]], - request: eventarc.ListPipelinesRequest, - response: eventarc.ListPipelinesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListPipelinesRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListPipelinesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListPipelinesRequest(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[eventarc.ListPipelinesResponse]: - 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[pipeline.Pipeline]: - async def async_generator(): - async for page in self.pages: - for response in page.pipelines: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGoogleApiSourcesPager: - """A pager for iterating through ``list_google_api_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``google_api_sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListGoogleApiSources`` requests and continue to iterate - through the ``google_api_sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., eventarc.ListGoogleApiSourcesResponse], - request: eventarc.ListGoogleApiSourcesRequest, - response: eventarc.ListGoogleApiSourcesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListGoogleApiSourcesRequest(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[eventarc.ListGoogleApiSourcesResponse]: - 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[google_api_source.GoogleApiSource]: - for page in self.pages: - yield from page.google_api_sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGoogleApiSourcesAsyncPager: - """A pager for iterating through ``list_google_api_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``google_api_sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListGoogleApiSources`` requests and continue to iterate - through the ``google_api_sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` - attributes are available on the 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[eventarc.ListGoogleApiSourcesResponse]], - request: eventarc.ListGoogleApiSourcesRequest, - response: eventarc.ListGoogleApiSourcesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest): - The initial request object. - response (google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = eventarc.ListGoogleApiSourcesRequest(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[eventarc.ListGoogleApiSourcesResponse]: - 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[google_api_source.GoogleApiSource]: - async def async_generator(): - async for page in self.pages: - for response in page.google_api_sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst deleted file mode 100644 index 442d2fb0c1b2..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`EventarcTransport` is the ABC for all transports. -- public child `EventarcGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `EventarcGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseEventarcRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `EventarcRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py deleted file mode 100644 index afed78b17c2c..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 EventarcTransport -from .grpc import EventarcGrpcTransport -from .grpc_asyncio import EventarcGrpcAsyncIOTransport -from .rest import EventarcRestTransport -from .rest import EventarcRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EventarcTransport]] -_transport_registry['grpc'] = EventarcGrpcTransport -_transport_registry['grpc_asyncio'] = EventarcGrpcAsyncIOTransport -_transport_registry['rest'] = EventarcRestTransport - -__all__ = ( - 'EventarcTransport', - 'EventarcGrpcTransport', - 'EventarcGrpcAsyncIOTransport', - 'EventarcRestTransport', - 'EventarcRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py deleted file mode 100644 index 9c0558d2afd3..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ /dev/null @@ -1,1013 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.eventarc_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -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 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EventarcTransport(abc.ABC): - """Abstract transport class for Eventarc.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'eventarc.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: 'eventarc.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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if 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.get_trigger: gapic_v1.method.wrap_method( - self.get_trigger, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_triggers: gapic_v1.method.wrap_method( - self.list_triggers, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_trigger: gapic_v1.method.wrap_method( - self.create_trigger, - default_timeout=60.0, - client_info=client_info, - ), - self.update_trigger: gapic_v1.method.wrap_method( - self.update_trigger, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_trigger: gapic_v1.method.wrap_method( - self.delete_trigger, - default_timeout=60.0, - client_info=client_info, - ), - self.get_channel: gapic_v1.method.wrap_method( - self.get_channel, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_channels: gapic_v1.method.wrap_method( - self.list_channels, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_channel_: gapic_v1.method.wrap_method( - self.create_channel_, - default_timeout=60.0, - client_info=client_info, - ), - self.update_channel: gapic_v1.method.wrap_method( - self.update_channel, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_channel: gapic_v1.method.wrap_method( - self.delete_channel, - default_timeout=60.0, - client_info=client_info, - ), - self.get_provider: gapic_v1.method.wrap_method( - self.get_provider, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_providers: gapic_v1.method.wrap_method( - self.list_providers, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_channel_connection: gapic_v1.method.wrap_method( - self.get_channel_connection, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_channel_connections: gapic_v1.method.wrap_method( - self.list_channel_connections, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_channel_connection: gapic_v1.method.wrap_method( - self.create_channel_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_channel_connection: gapic_v1.method.wrap_method( - self.delete_channel_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.get_google_channel_config: gapic_v1.method.wrap_method( - self.get_google_channel_config, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_google_channel_config: gapic_v1.method.wrap_method( - self.update_google_channel_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_message_bus: gapic_v1.method.wrap_method( - self.get_message_bus, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_message_buses: gapic_v1.method.wrap_method( - self.list_message_buses, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_message_bus_enrollments: gapic_v1.method.wrap_method( - self.list_message_bus_enrollments, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_message_bus: gapic_v1.method.wrap_method( - self.create_message_bus, - default_timeout=60.0, - client_info=client_info, - ), - self.update_message_bus: gapic_v1.method.wrap_method( - self.update_message_bus, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_message_bus: gapic_v1.method.wrap_method( - self.delete_message_bus, - default_timeout=60.0, - client_info=client_info, - ), - self.get_enrollment: gapic_v1.method.wrap_method( - self.get_enrollment, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_enrollments: gapic_v1.method.wrap_method( - self.list_enrollments, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_enrollment: gapic_v1.method.wrap_method( - self.create_enrollment, - default_timeout=60.0, - client_info=client_info, - ), - self.update_enrollment: gapic_v1.method.wrap_method( - self.update_enrollment, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_enrollment: gapic_v1.method.wrap_method( - self.delete_enrollment, - default_timeout=60.0, - client_info=client_info, - ), - self.get_pipeline: gapic_v1.method.wrap_method( - self.get_pipeline, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_pipelines: gapic_v1.method.wrap_method( - self.list_pipelines, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_pipeline: gapic_v1.method.wrap_method( - self.create_pipeline, - default_timeout=60.0, - client_info=client_info, - ), - self.update_pipeline: gapic_v1.method.wrap_method( - self.update_pipeline, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_pipeline: gapic_v1.method.wrap_method( - self.delete_pipeline, - default_timeout=60.0, - client_info=client_info, - ), - self.get_google_api_source: gapic_v1.method.wrap_method( - self.get_google_api_source, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_google_api_sources: gapic_v1.method.wrap_method( - self.list_google_api_sources, - default_retry=retries.Retry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_google_api_source: gapic_v1.method.wrap_method( - self.create_google_api_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_google_api_source: gapic_v1.method.wrap_method( - self.update_google_api_source, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_google_api_source: gapic_v1.method.wrap_method( - self.delete_google_api_source, - 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.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - Union[ - trigger.Trigger, - Awaitable[trigger.Trigger] - ]]: - raise NotImplementedError() - - @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - Union[ - eventarc.ListTriggersResponse, - Awaitable[eventarc.ListTriggersResponse] - ]]: - raise NotImplementedError() - - @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - Union[ - channel.Channel, - Awaitable[channel.Channel] - ]]: - raise NotImplementedError() - - @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - Union[ - eventarc.ListChannelsResponse, - Awaitable[eventarc.ListChannelsResponse] - ]]: - raise NotImplementedError() - - @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - Union[ - discovery.Provider, - Awaitable[discovery.Provider] - ]]: - raise NotImplementedError() - - @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - Union[ - eventarc.ListProvidersResponse, - Awaitable[eventarc.ListProvidersResponse] - ]]: - raise NotImplementedError() - - @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - Union[ - channel_connection.ChannelConnection, - Awaitable[channel_connection.ChannelConnection] - ]]: - raise NotImplementedError() - - @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - Union[ - eventarc.ListChannelConnectionsResponse, - Awaitable[eventarc.ListChannelConnectionsResponse] - ]]: - raise NotImplementedError() - - @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - Union[ - google_channel_config.GoogleChannelConfig, - Awaitable[google_channel_config.GoogleChannelConfig] - ]]: - raise NotImplementedError() - - @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - Union[ - gce_google_channel_config.GoogleChannelConfig, - Awaitable[gce_google_channel_config.GoogleChannelConfig] - ]]: - raise NotImplementedError() - - @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - Union[ - message_bus.MessageBus, - Awaitable[message_bus.MessageBus] - ]]: - raise NotImplementedError() - - @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - Union[ - eventarc.ListMessageBusesResponse, - Awaitable[eventarc.ListMessageBusesResponse] - ]]: - raise NotImplementedError() - - @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - Union[ - eventarc.ListMessageBusEnrollmentsResponse, - Awaitable[eventarc.ListMessageBusEnrollmentsResponse] - ]]: - raise NotImplementedError() - - @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - Union[ - enrollment.Enrollment, - Awaitable[enrollment.Enrollment] - ]]: - raise NotImplementedError() - - @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - Union[ - eventarc.ListEnrollmentsResponse, - Awaitable[eventarc.ListEnrollmentsResponse] - ]]: - raise NotImplementedError() - - @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - Union[ - pipeline.Pipeline, - Awaitable[pipeline.Pipeline] - ]]: - raise NotImplementedError() - - @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - Union[ - eventarc.ListPipelinesResponse, - Awaitable[eventarc.ListPipelinesResponse] - ]]: - raise NotImplementedError() - - @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - Union[ - google_api_source.GoogleApiSource, - Awaitable[google_api_source.GoogleApiSource] - ]]: - raise NotImplementedError() - - @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - Union[ - eventarc.ListGoogleApiSourcesResponse, - Awaitable[eventarc.ListGoogleApiSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - 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__ = ( - 'EventarcTransport', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py deleted file mode 100644 index 4fa4923170a2..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ /dev/null @@ -1,1486 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -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 .base import EventarcTransport, DEFAULT_CLIENT_INFO - - -class EventarcGrpcTransport(EventarcTransport): - """gRPC backend transport for Eventarc. - - Eventarc allows users to subscribe to various events that are - provided by Google Cloud services and forward them to supported - destinations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'eventarc.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: 'eventarc.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]): 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. - 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'eventarc.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - trigger.Trigger]: - r"""Return a callable for the get trigger method over gRPC. - - Get a single trigger. - - Returns: - Callable[[~.GetTriggerRequest], - ~.Trigger]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_trigger' not in self._stubs: - self._stubs['get_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetTrigger', - request_serializer=eventarc.GetTriggerRequest.serialize, - response_deserializer=trigger.Trigger.deserialize, - ) - return self._stubs['get_trigger'] - - @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - eventarc.ListTriggersResponse]: - r"""Return a callable for the list triggers method over gRPC. - - List triggers. - - Returns: - Callable[[~.ListTriggersRequest], - ~.ListTriggersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_triggers' not in self._stubs: - self._stubs['list_triggers'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListTriggers', - request_serializer=eventarc.ListTriggersRequest.serialize, - response_deserializer=eventarc.ListTriggersResponse.deserialize, - ) - return self._stubs['list_triggers'] - - @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - operations_pb2.Operation]: - r"""Return a callable for the create trigger method over gRPC. - - Create a new trigger in a particular project and - location. - - Returns: - Callable[[~.CreateTriggerRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_trigger' not in self._stubs: - self._stubs['create_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateTrigger', - request_serializer=eventarc.CreateTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_trigger'] - - @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - operations_pb2.Operation]: - r"""Return a callable for the update trigger method over gRPC. - - Update a single trigger. - - Returns: - Callable[[~.UpdateTriggerRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_trigger' not in self._stubs: - self._stubs['update_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', - request_serializer=eventarc.UpdateTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_trigger'] - - @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete trigger method over gRPC. - - Delete a single trigger. - - Returns: - Callable[[~.DeleteTriggerRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_trigger' not in self._stubs: - self._stubs['delete_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', - request_serializer=eventarc.DeleteTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_trigger'] - - @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - channel.Channel]: - r"""Return a callable for the get channel method over gRPC. - - Get a single Channel. - - Returns: - Callable[[~.GetChannelRequest], - ~.Channel]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_channel' not in self._stubs: - self._stubs['get_channel'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetChannel', - request_serializer=eventarc.GetChannelRequest.serialize, - response_deserializer=channel.Channel.deserialize, - ) - return self._stubs['get_channel'] - - @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - eventarc.ListChannelsResponse]: - r"""Return a callable for the list channels method over gRPC. - - List channels. - - Returns: - Callable[[~.ListChannelsRequest], - ~.ListChannelsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_channels' not in self._stubs: - self._stubs['list_channels'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListChannels', - request_serializer=eventarc.ListChannelsRequest.serialize, - response_deserializer=eventarc.ListChannelsResponse.deserialize, - ) - return self._stubs['list_channels'] - - @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - operations_pb2.Operation]: - r"""Return a callable for the create channel method over gRPC. - - Create a new channel in a particular project and - location. - - Returns: - Callable[[~.CreateChannelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_channel_' not in self._stubs: - self._stubs['create_channel_'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateChannel', - request_serializer=eventarc.CreateChannelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_channel_'] - - @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - operations_pb2.Operation]: - r"""Return a callable for the update channel method over gRPC. - - Update a single channel. - - Returns: - Callable[[~.UpdateChannelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_channel' not in self._stubs: - self._stubs['update_channel'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateChannel', - request_serializer=eventarc.UpdateChannelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_channel'] - - @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete channel method over gRPC. - - Delete a single channel. - - Returns: - Callable[[~.DeleteChannelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_channel' not in self._stubs: - self._stubs['delete_channel'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteChannel', - request_serializer=eventarc.DeleteChannelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_channel'] - - @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - discovery.Provider]: - r"""Return a callable for the get provider method over gRPC. - - Get a single Provider. - - Returns: - Callable[[~.GetProviderRequest], - ~.Provider]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_provider' not in self._stubs: - self._stubs['get_provider'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetProvider', - request_serializer=eventarc.GetProviderRequest.serialize, - response_deserializer=discovery.Provider.deserialize, - ) - return self._stubs['get_provider'] - - @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - eventarc.ListProvidersResponse]: - r"""Return a callable for the list providers method over gRPC. - - List providers. - - Returns: - Callable[[~.ListProvidersRequest], - ~.ListProvidersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_providers' not in self._stubs: - self._stubs['list_providers'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListProviders', - request_serializer=eventarc.ListProvidersRequest.serialize, - response_deserializer=eventarc.ListProvidersResponse.deserialize, - ) - return self._stubs['list_providers'] - - @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - channel_connection.ChannelConnection]: - r"""Return a callable for the get channel connection method over gRPC. - - Get a single ChannelConnection. - - Returns: - Callable[[~.GetChannelConnectionRequest], - ~.ChannelConnection]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_channel_connection' not in self._stubs: - self._stubs['get_channel_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', - request_serializer=eventarc.GetChannelConnectionRequest.serialize, - response_deserializer=channel_connection.ChannelConnection.deserialize, - ) - return self._stubs['get_channel_connection'] - - @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - eventarc.ListChannelConnectionsResponse]: - r"""Return a callable for the list channel connections method over gRPC. - - List channel connections. - - Returns: - Callable[[~.ListChannelConnectionsRequest], - ~.ListChannelConnectionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_channel_connections' not in self._stubs: - self._stubs['list_channel_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', - request_serializer=eventarc.ListChannelConnectionsRequest.serialize, - response_deserializer=eventarc.ListChannelConnectionsResponse.deserialize, - ) - return self._stubs['list_channel_connections'] - - @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create channel connection method over gRPC. - - Create a new ChannelConnection in a particular - project and location. - - Returns: - Callable[[~.CreateChannelConnectionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_channel_connection' not in self._stubs: - self._stubs['create_channel_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', - request_serializer=eventarc.CreateChannelConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_channel_connection'] - - @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete channel connection method over gRPC. - - Delete a single ChannelConnection. - - Returns: - Callable[[~.DeleteChannelConnectionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_channel_connection' not in self._stubs: - self._stubs['delete_channel_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', - request_serializer=eventarc.DeleteChannelConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_channel_connection'] - - @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - google_channel_config.GoogleChannelConfig]: - r"""Return a callable for the get google channel config method over gRPC. - - Get a GoogleChannelConfig - - Returns: - Callable[[~.GetGoogleChannelConfigRequest], - ~.GoogleChannelConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_google_channel_config' not in self._stubs: - self._stubs['get_google_channel_config'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig', - request_serializer=eventarc.GetGoogleChannelConfigRequest.serialize, - response_deserializer=google_channel_config.GoogleChannelConfig.deserialize, - ) - return self._stubs['get_google_channel_config'] - - @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - gce_google_channel_config.GoogleChannelConfig]: - r"""Return a callable for the update google channel config method over gRPC. - - Update a single GoogleChannelConfig - - Returns: - Callable[[~.UpdateGoogleChannelConfigRequest], - ~.GoogleChannelConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_google_channel_config' not in self._stubs: - self._stubs['update_google_channel_config'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig', - request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, - response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, - ) - return self._stubs['update_google_channel_config'] - - @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - message_bus.MessageBus]: - r"""Return a callable for the get message bus method over gRPC. - - Get a single MessageBus. - - Returns: - Callable[[~.GetMessageBusRequest], - ~.MessageBus]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_message_bus' not in self._stubs: - self._stubs['get_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetMessageBus', - request_serializer=eventarc.GetMessageBusRequest.serialize, - response_deserializer=message_bus.MessageBus.deserialize, - ) - return self._stubs['get_message_bus'] - - @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - eventarc.ListMessageBusesResponse]: - r"""Return a callable for the list message buses method over gRPC. - - List message buses. - - Returns: - Callable[[~.ListMessageBusesRequest], - ~.ListMessageBusesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_message_buses' not in self._stubs: - self._stubs['list_message_buses'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListMessageBuses', - request_serializer=eventarc.ListMessageBusesRequest.serialize, - response_deserializer=eventarc.ListMessageBusesResponse.deserialize, - ) - return self._stubs['list_message_buses'] - - @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - eventarc.ListMessageBusEnrollmentsResponse]: - r"""Return a callable for the list message bus enrollments method over gRPC. - - List message bus enrollments. - - Returns: - Callable[[~.ListMessageBusEnrollmentsRequest], - ~.ListMessageBusEnrollmentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_message_bus_enrollments' not in self._stubs: - self._stubs['list_message_bus_enrollments'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments', - request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, - response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, - ) - return self._stubs['list_message_bus_enrollments'] - - @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - operations_pb2.Operation]: - r"""Return a callable for the create message bus method over gRPC. - - Create a new MessageBus in a particular project and - location. - - Returns: - Callable[[~.CreateMessageBusRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_message_bus' not in self._stubs: - self._stubs['create_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateMessageBus', - request_serializer=eventarc.CreateMessageBusRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_message_bus'] - - @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - operations_pb2.Operation]: - r"""Return a callable for the update message bus method over gRPC. - - Update a single message bus. - - Returns: - Callable[[~.UpdateMessageBusRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_message_bus' not in self._stubs: - self._stubs['update_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus', - request_serializer=eventarc.UpdateMessageBusRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_message_bus'] - - @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete message bus method over gRPC. - - Delete a single message bus. - - Returns: - Callable[[~.DeleteMessageBusRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_message_bus' not in self._stubs: - self._stubs['delete_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus', - request_serializer=eventarc.DeleteMessageBusRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_message_bus'] - - @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - enrollment.Enrollment]: - r"""Return a callable for the get enrollment method over gRPC. - - Get a single Enrollment. - - Returns: - Callable[[~.GetEnrollmentRequest], - ~.Enrollment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_enrollment' not in self._stubs: - self._stubs['get_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetEnrollment', - request_serializer=eventarc.GetEnrollmentRequest.serialize, - response_deserializer=enrollment.Enrollment.deserialize, - ) - return self._stubs['get_enrollment'] - - @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - eventarc.ListEnrollmentsResponse]: - r"""Return a callable for the list enrollments method over gRPC. - - List Enrollments. - - Returns: - Callable[[~.ListEnrollmentsRequest], - ~.ListEnrollmentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_enrollments' not in self._stubs: - self._stubs['list_enrollments'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListEnrollments', - request_serializer=eventarc.ListEnrollmentsRequest.serialize, - response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, - ) - return self._stubs['list_enrollments'] - - @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create enrollment method over gRPC. - - Create a new Enrollment in a particular project and - location. - - Returns: - Callable[[~.CreateEnrollmentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_enrollment' not in self._stubs: - self._stubs['create_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateEnrollment', - request_serializer=eventarc.CreateEnrollmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_enrollment'] - - @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update enrollment method over gRPC. - - Update a single Enrollment. - - Returns: - Callable[[~.UpdateEnrollmentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_enrollment' not in self._stubs: - self._stubs['update_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment', - request_serializer=eventarc.UpdateEnrollmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_enrollment'] - - @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete enrollment method over gRPC. - - Delete a single Enrollment. - - Returns: - Callable[[~.DeleteEnrollmentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_enrollment' not in self._stubs: - self._stubs['delete_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment', - request_serializer=eventarc.DeleteEnrollmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_enrollment'] - - @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - pipeline.Pipeline]: - r"""Return a callable for the get pipeline method over gRPC. - - Get a single Pipeline. - - Returns: - Callable[[~.GetPipelineRequest], - ~.Pipeline]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_pipeline' not in self._stubs: - self._stubs['get_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetPipeline', - request_serializer=eventarc.GetPipelineRequest.serialize, - response_deserializer=pipeline.Pipeline.deserialize, - ) - return self._stubs['get_pipeline'] - - @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - eventarc.ListPipelinesResponse]: - r"""Return a callable for the list pipelines method over gRPC. - - List pipelines. - - Returns: - Callable[[~.ListPipelinesRequest], - ~.ListPipelinesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_pipelines' not in self._stubs: - self._stubs['list_pipelines'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListPipelines', - request_serializer=eventarc.ListPipelinesRequest.serialize, - response_deserializer=eventarc.ListPipelinesResponse.deserialize, - ) - return self._stubs['list_pipelines'] - - @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - operations_pb2.Operation]: - r"""Return a callable for the create pipeline method over gRPC. - - Create a new Pipeline in a particular project and - location. - - Returns: - Callable[[~.CreatePipelineRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_pipeline' not in self._stubs: - self._stubs['create_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreatePipeline', - request_serializer=eventarc.CreatePipelineRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_pipeline'] - - @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - operations_pb2.Operation]: - r"""Return a callable for the update pipeline method over gRPC. - - Update a single pipeline. - - Returns: - Callable[[~.UpdatePipelineRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_pipeline' not in self._stubs: - self._stubs['update_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdatePipeline', - request_serializer=eventarc.UpdatePipelineRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_pipeline'] - - @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete pipeline method over gRPC. - - Delete a single pipeline. - - Returns: - Callable[[~.DeletePipelineRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_pipeline' not in self._stubs: - self._stubs['delete_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeletePipeline', - request_serializer=eventarc.DeletePipelineRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_pipeline'] - - @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - google_api_source.GoogleApiSource]: - r"""Return a callable for the get google api source method over gRPC. - - Get a single GoogleApiSource. - - Returns: - Callable[[~.GetGoogleApiSourceRequest], - ~.GoogleApiSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_google_api_source' not in self._stubs: - self._stubs['get_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource', - request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, - response_deserializer=google_api_source.GoogleApiSource.deserialize, - ) - return self._stubs['get_google_api_source'] - - @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - eventarc.ListGoogleApiSourcesResponse]: - r"""Return a callable for the list google api sources method over gRPC. - - List GoogleApiSources. - - Returns: - Callable[[~.ListGoogleApiSourcesRequest], - ~.ListGoogleApiSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_google_api_sources' not in self._stubs: - self._stubs['list_google_api_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources', - request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, - response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, - ) - return self._stubs['list_google_api_sources'] - - @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - operations_pb2.Operation]: - r"""Return a callable for the create google api source method over gRPC. - - Create a new GoogleApiSource in a particular project - and location. - - Returns: - Callable[[~.CreateGoogleApiSourceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_google_api_source' not in self._stubs: - self._stubs['create_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource', - request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_google_api_source'] - - @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - operations_pb2.Operation]: - r"""Return a callable for the update google api source method over gRPC. - - Update a single GoogleApiSource. - - Returns: - Callable[[~.UpdateGoogleApiSourceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_google_api_source' not in self._stubs: - self._stubs['update_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource', - request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_google_api_source'] - - @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete google api source method over gRPC. - - Delete a single GoogleApiSource. - - Returns: - Callable[[~.DeleteGoogleApiSourceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_google_api_source' not in self._stubs: - self._stubs['delete_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource', - request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_google_api_source'] - - def close(self): - self.grpc_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.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def 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.grpc_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.grpc_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.grpc_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__ = ( - 'EventarcGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py deleted file mode 100644 index 9411c3f57461..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py +++ /dev/null @@ -1,1922 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -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 .base import EventarcTransport, DEFAULT_CLIENT_INFO -from .grpc import EventarcGrpcTransport - - -class EventarcGrpcAsyncIOTransport(EventarcTransport): - """gRPC AsyncIO backend transport for Eventarc. - - Eventarc allows users to subscribe to various events that are - provided by Google Cloud services and forward them to supported - destinations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'eventarc.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (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 = 'eventarc.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: 'eventarc.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]): 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. - scopes (Optional[Sequence[str]]): A optional 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - Awaitable[trigger.Trigger]]: - r"""Return a callable for the get trigger method over gRPC. - - Get a single trigger. - - Returns: - Callable[[~.GetTriggerRequest], - Awaitable[~.Trigger]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_trigger' not in self._stubs: - self._stubs['get_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetTrigger', - request_serializer=eventarc.GetTriggerRequest.serialize, - response_deserializer=trigger.Trigger.deserialize, - ) - return self._stubs['get_trigger'] - - @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - Awaitable[eventarc.ListTriggersResponse]]: - r"""Return a callable for the list triggers method over gRPC. - - List triggers. - - Returns: - Callable[[~.ListTriggersRequest], - Awaitable[~.ListTriggersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_triggers' not in self._stubs: - self._stubs['list_triggers'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListTriggers', - request_serializer=eventarc.ListTriggersRequest.serialize, - response_deserializer=eventarc.ListTriggersResponse.deserialize, - ) - return self._stubs['list_triggers'] - - @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create trigger method over gRPC. - - Create a new trigger in a particular project and - location. - - Returns: - Callable[[~.CreateTriggerRequest], - 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_trigger' not in self._stubs: - self._stubs['create_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateTrigger', - request_serializer=eventarc.CreateTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_trigger'] - - @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update trigger method over gRPC. - - Update a single trigger. - - Returns: - Callable[[~.UpdateTriggerRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_trigger' not in self._stubs: - self._stubs['update_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', - request_serializer=eventarc.UpdateTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_trigger'] - - @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete trigger method over gRPC. - - Delete a single trigger. - - Returns: - Callable[[~.DeleteTriggerRequest], - 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_trigger' not in self._stubs: - self._stubs['delete_trigger'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', - request_serializer=eventarc.DeleteTriggerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_trigger'] - - @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - Awaitable[channel.Channel]]: - r"""Return a callable for the get channel method over gRPC. - - Get a single Channel. - - Returns: - Callable[[~.GetChannelRequest], - Awaitable[~.Channel]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_channel' not in self._stubs: - self._stubs['get_channel'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetChannel', - request_serializer=eventarc.GetChannelRequest.serialize, - response_deserializer=channel.Channel.deserialize, - ) - return self._stubs['get_channel'] - - @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - Awaitable[eventarc.ListChannelsResponse]]: - r"""Return a callable for the list channels method over gRPC. - - List channels. - - Returns: - Callable[[~.ListChannelsRequest], - Awaitable[~.ListChannelsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_channels' not in self._stubs: - self._stubs['list_channels'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListChannels', - request_serializer=eventarc.ListChannelsRequest.serialize, - response_deserializer=eventarc.ListChannelsResponse.deserialize, - ) - return self._stubs['list_channels'] - - @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create channel method over gRPC. - - Create a new channel in a particular project and - location. - - Returns: - Callable[[~.CreateChannelRequest], - 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_channel_' not in self._stubs: - self._stubs['create_channel_'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateChannel', - request_serializer=eventarc.CreateChannelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_channel_'] - - @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update channel method over gRPC. - - Update a single channel. - - Returns: - Callable[[~.UpdateChannelRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_channel' not in self._stubs: - self._stubs['update_channel'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateChannel', - request_serializer=eventarc.UpdateChannelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_channel'] - - @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete channel method over gRPC. - - Delete a single channel. - - Returns: - Callable[[~.DeleteChannelRequest], - 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_channel' not in self._stubs: - self._stubs['delete_channel'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteChannel', - request_serializer=eventarc.DeleteChannelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_channel'] - - @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - Awaitable[discovery.Provider]]: - r"""Return a callable for the get provider method over gRPC. - - Get a single Provider. - - Returns: - Callable[[~.GetProviderRequest], - Awaitable[~.Provider]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_provider' not in self._stubs: - self._stubs['get_provider'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetProvider', - request_serializer=eventarc.GetProviderRequest.serialize, - response_deserializer=discovery.Provider.deserialize, - ) - return self._stubs['get_provider'] - - @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - Awaitable[eventarc.ListProvidersResponse]]: - r"""Return a callable for the list providers method over gRPC. - - List providers. - - Returns: - Callable[[~.ListProvidersRequest], - Awaitable[~.ListProvidersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_providers' not in self._stubs: - self._stubs['list_providers'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListProviders', - request_serializer=eventarc.ListProvidersRequest.serialize, - response_deserializer=eventarc.ListProvidersResponse.deserialize, - ) - return self._stubs['list_providers'] - - @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - Awaitable[channel_connection.ChannelConnection]]: - r"""Return a callable for the get channel connection method over gRPC. - - Get a single ChannelConnection. - - Returns: - Callable[[~.GetChannelConnectionRequest], - Awaitable[~.ChannelConnection]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_channel_connection' not in self._stubs: - self._stubs['get_channel_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', - request_serializer=eventarc.GetChannelConnectionRequest.serialize, - response_deserializer=channel_connection.ChannelConnection.deserialize, - ) - return self._stubs['get_channel_connection'] - - @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - Awaitable[eventarc.ListChannelConnectionsResponse]]: - r"""Return a callable for the list channel connections method over gRPC. - - List channel connections. - - Returns: - Callable[[~.ListChannelConnectionsRequest], - Awaitable[~.ListChannelConnectionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_channel_connections' not in self._stubs: - self._stubs['list_channel_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', - request_serializer=eventarc.ListChannelConnectionsRequest.serialize, - response_deserializer=eventarc.ListChannelConnectionsResponse.deserialize, - ) - return self._stubs['list_channel_connections'] - - @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create channel connection method over gRPC. - - Create a new ChannelConnection in a particular - project and location. - - Returns: - Callable[[~.CreateChannelConnectionRequest], - 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_channel_connection' not in self._stubs: - self._stubs['create_channel_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', - request_serializer=eventarc.CreateChannelConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_channel_connection'] - - @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete channel connection method over gRPC. - - Delete a single ChannelConnection. - - Returns: - Callable[[~.DeleteChannelConnectionRequest], - 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_channel_connection' not in self._stubs: - self._stubs['delete_channel_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', - request_serializer=eventarc.DeleteChannelConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_channel_connection'] - - @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - Awaitable[google_channel_config.GoogleChannelConfig]]: - r"""Return a callable for the get google channel config method over gRPC. - - Get a GoogleChannelConfig - - Returns: - Callable[[~.GetGoogleChannelConfigRequest], - Awaitable[~.GoogleChannelConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_google_channel_config' not in self._stubs: - self._stubs['get_google_channel_config'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig', - request_serializer=eventarc.GetGoogleChannelConfigRequest.serialize, - response_deserializer=google_channel_config.GoogleChannelConfig.deserialize, - ) - return self._stubs['get_google_channel_config'] - - @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - Awaitable[gce_google_channel_config.GoogleChannelConfig]]: - r"""Return a callable for the update google channel config method over gRPC. - - Update a single GoogleChannelConfig - - Returns: - Callable[[~.UpdateGoogleChannelConfigRequest], - Awaitable[~.GoogleChannelConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_google_channel_config' not in self._stubs: - self._stubs['update_google_channel_config'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig', - request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, - response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, - ) - return self._stubs['update_google_channel_config'] - - @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - Awaitable[message_bus.MessageBus]]: - r"""Return a callable for the get message bus method over gRPC. - - Get a single MessageBus. - - Returns: - Callable[[~.GetMessageBusRequest], - Awaitable[~.MessageBus]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_message_bus' not in self._stubs: - self._stubs['get_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetMessageBus', - request_serializer=eventarc.GetMessageBusRequest.serialize, - response_deserializer=message_bus.MessageBus.deserialize, - ) - return self._stubs['get_message_bus'] - - @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - Awaitable[eventarc.ListMessageBusesResponse]]: - r"""Return a callable for the list message buses method over gRPC. - - List message buses. - - Returns: - Callable[[~.ListMessageBusesRequest], - Awaitable[~.ListMessageBusesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_message_buses' not in self._stubs: - self._stubs['list_message_buses'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListMessageBuses', - request_serializer=eventarc.ListMessageBusesRequest.serialize, - response_deserializer=eventarc.ListMessageBusesResponse.deserialize, - ) - return self._stubs['list_message_buses'] - - @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - Awaitable[eventarc.ListMessageBusEnrollmentsResponse]]: - r"""Return a callable for the list message bus enrollments method over gRPC. - - List message bus enrollments. - - Returns: - Callable[[~.ListMessageBusEnrollmentsRequest], - Awaitable[~.ListMessageBusEnrollmentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_message_bus_enrollments' not in self._stubs: - self._stubs['list_message_bus_enrollments'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments', - request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, - response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, - ) - return self._stubs['list_message_bus_enrollments'] - - @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create message bus method over gRPC. - - Create a new MessageBus in a particular project and - location. - - Returns: - Callable[[~.CreateMessageBusRequest], - 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_message_bus' not in self._stubs: - self._stubs['create_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateMessageBus', - request_serializer=eventarc.CreateMessageBusRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_message_bus'] - - @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update message bus method over gRPC. - - Update a single message bus. - - Returns: - Callable[[~.UpdateMessageBusRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_message_bus' not in self._stubs: - self._stubs['update_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus', - request_serializer=eventarc.UpdateMessageBusRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_message_bus'] - - @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete message bus method over gRPC. - - Delete a single message bus. - - Returns: - Callable[[~.DeleteMessageBusRequest], - 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_message_bus' not in self._stubs: - self._stubs['delete_message_bus'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus', - request_serializer=eventarc.DeleteMessageBusRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_message_bus'] - - @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - Awaitable[enrollment.Enrollment]]: - r"""Return a callable for the get enrollment method over gRPC. - - Get a single Enrollment. - - Returns: - Callable[[~.GetEnrollmentRequest], - Awaitable[~.Enrollment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_enrollment' not in self._stubs: - self._stubs['get_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetEnrollment', - request_serializer=eventarc.GetEnrollmentRequest.serialize, - response_deserializer=enrollment.Enrollment.deserialize, - ) - return self._stubs['get_enrollment'] - - @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - Awaitable[eventarc.ListEnrollmentsResponse]]: - r"""Return a callable for the list enrollments method over gRPC. - - List Enrollments. - - Returns: - Callable[[~.ListEnrollmentsRequest], - Awaitable[~.ListEnrollmentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_enrollments' not in self._stubs: - self._stubs['list_enrollments'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListEnrollments', - request_serializer=eventarc.ListEnrollmentsRequest.serialize, - response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, - ) - return self._stubs['list_enrollments'] - - @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create enrollment method over gRPC. - - Create a new Enrollment in a particular project and - location. - - Returns: - Callable[[~.CreateEnrollmentRequest], - 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_enrollment' not in self._stubs: - self._stubs['create_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateEnrollment', - request_serializer=eventarc.CreateEnrollmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_enrollment'] - - @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update enrollment method over gRPC. - - Update a single Enrollment. - - Returns: - Callable[[~.UpdateEnrollmentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_enrollment' not in self._stubs: - self._stubs['update_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment', - request_serializer=eventarc.UpdateEnrollmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_enrollment'] - - @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete enrollment method over gRPC. - - Delete a single Enrollment. - - Returns: - Callable[[~.DeleteEnrollmentRequest], - 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_enrollment' not in self._stubs: - self._stubs['delete_enrollment'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment', - request_serializer=eventarc.DeleteEnrollmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_enrollment'] - - @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - Awaitable[pipeline.Pipeline]]: - r"""Return a callable for the get pipeline method over gRPC. - - Get a single Pipeline. - - Returns: - Callable[[~.GetPipelineRequest], - Awaitable[~.Pipeline]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_pipeline' not in self._stubs: - self._stubs['get_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetPipeline', - request_serializer=eventarc.GetPipelineRequest.serialize, - response_deserializer=pipeline.Pipeline.deserialize, - ) - return self._stubs['get_pipeline'] - - @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - Awaitable[eventarc.ListPipelinesResponse]]: - r"""Return a callable for the list pipelines method over gRPC. - - List pipelines. - - Returns: - Callable[[~.ListPipelinesRequest], - Awaitable[~.ListPipelinesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_pipelines' not in self._stubs: - self._stubs['list_pipelines'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListPipelines', - request_serializer=eventarc.ListPipelinesRequest.serialize, - response_deserializer=eventarc.ListPipelinesResponse.deserialize, - ) - return self._stubs['list_pipelines'] - - @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create pipeline method over gRPC. - - Create a new Pipeline in a particular project and - location. - - Returns: - Callable[[~.CreatePipelineRequest], - 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_pipeline' not in self._stubs: - self._stubs['create_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreatePipeline', - request_serializer=eventarc.CreatePipelineRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_pipeline'] - - @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update pipeline method over gRPC. - - Update a single pipeline. - - Returns: - Callable[[~.UpdatePipelineRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_pipeline' not in self._stubs: - self._stubs['update_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdatePipeline', - request_serializer=eventarc.UpdatePipelineRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_pipeline'] - - @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete pipeline method over gRPC. - - Delete a single pipeline. - - Returns: - Callable[[~.DeletePipelineRequest], - 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_pipeline' not in self._stubs: - self._stubs['delete_pipeline'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeletePipeline', - request_serializer=eventarc.DeletePipelineRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_pipeline'] - - @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - Awaitable[google_api_source.GoogleApiSource]]: - r"""Return a callable for the get google api source method over gRPC. - - Get a single GoogleApiSource. - - Returns: - Callable[[~.GetGoogleApiSourceRequest], - Awaitable[~.GoogleApiSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_google_api_source' not in self._stubs: - self._stubs['get_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource', - request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, - response_deserializer=google_api_source.GoogleApiSource.deserialize, - ) - return self._stubs['get_google_api_source'] - - @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - Awaitable[eventarc.ListGoogleApiSourcesResponse]]: - r"""Return a callable for the list google api sources method over gRPC. - - List GoogleApiSources. - - Returns: - Callable[[~.ListGoogleApiSourcesRequest], - Awaitable[~.ListGoogleApiSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_google_api_sources' not in self._stubs: - self._stubs['list_google_api_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources', - request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, - response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, - ) - return self._stubs['list_google_api_sources'] - - @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create google api source method over gRPC. - - Create a new GoogleApiSource in a particular project - and location. - - Returns: - Callable[[~.CreateGoogleApiSourceRequest], - 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_google_api_source' not in self._stubs: - self._stubs['create_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource', - request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_google_api_source'] - - @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update google api source method over gRPC. - - Update a single GoogleApiSource. - - Returns: - Callable[[~.UpdateGoogleApiSourceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_google_api_source' not in self._stubs: - self._stubs['update_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource', - request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_google_api_source'] - - @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete google api source method over gRPC. - - Delete a single GoogleApiSource. - - Returns: - Callable[[~.DeleteGoogleApiSourceRequest], - 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_google_api_source' not in self._stubs: - self._stubs['delete_google_api_source'] = self.grpc_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource', - request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_google_api_source'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_trigger: self._wrap_method( - self.get_trigger, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_triggers: self._wrap_method( - self.list_triggers, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_trigger: self._wrap_method( - self.create_trigger, - default_timeout=60.0, - client_info=client_info, - ), - self.update_trigger: self._wrap_method( - self.update_trigger, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_trigger: self._wrap_method( - self.delete_trigger, - default_timeout=60.0, - client_info=client_info, - ), - self.get_channel: self._wrap_method( - self.get_channel, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_channels: self._wrap_method( - self.list_channels, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_channel_: self._wrap_method( - self.create_channel_, - default_timeout=60.0, - client_info=client_info, - ), - self.update_channel: self._wrap_method( - self.update_channel, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_channel: self._wrap_method( - self.delete_channel, - default_timeout=60.0, - client_info=client_info, - ), - self.get_provider: self._wrap_method( - self.get_provider, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_providers: self._wrap_method( - self.list_providers, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_channel_connection: self._wrap_method( - self.get_channel_connection, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_channel_connections: self._wrap_method( - self.list_channel_connections, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_channel_connection: self._wrap_method( - self.create_channel_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_channel_connection: self._wrap_method( - self.delete_channel_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.get_google_channel_config: self._wrap_method( - self.get_google_channel_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_google_channel_config: self._wrap_method( - self.update_google_channel_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_message_bus: self._wrap_method( - self.get_message_bus, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_message_buses: self._wrap_method( - self.list_message_buses, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_message_bus_enrollments: self._wrap_method( - self.list_message_bus_enrollments, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_message_bus: self._wrap_method( - self.create_message_bus, - default_timeout=60.0, - client_info=client_info, - ), - self.update_message_bus: self._wrap_method( - self.update_message_bus, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_message_bus: self._wrap_method( - self.delete_message_bus, - default_timeout=60.0, - client_info=client_info, - ), - self.get_enrollment: self._wrap_method( - self.get_enrollment, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_enrollments: self._wrap_method( - self.list_enrollments, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_enrollment: self._wrap_method( - self.create_enrollment, - default_timeout=60.0, - client_info=client_info, - ), - self.update_enrollment: self._wrap_method( - self.update_enrollment, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_enrollment: self._wrap_method( - self.delete_enrollment, - default_timeout=60.0, - client_info=client_info, - ), - self.get_pipeline: self._wrap_method( - self.get_pipeline, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_pipelines: self._wrap_method( - self.list_pipelines, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_pipeline: self._wrap_method( - self.create_pipeline, - default_timeout=60.0, - client_info=client_info, - ), - self.update_pipeline: self._wrap_method( - self.update_pipeline, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_pipeline: self._wrap_method( - self.delete_pipeline, - default_timeout=60.0, - client_info=client_info, - ), - self.get_google_api_source: self._wrap_method( - self.get_google_api_source, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_google_api_sources: self._wrap_method( - self.list_google_api_sources, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_google_api_source: self._wrap_method( - self.create_google_api_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_google_api_source: self._wrap_method( - self.update_google_api_source, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_google_api_source: self._wrap_method( - self.delete_google_api_source, - 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.cancel_operation: self._wrap_method( - self.cancel_operation, - 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, - ), - } - - 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.grpc_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.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def 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.grpc_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.grpc_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.grpc_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__ = ( - 'EventarcGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py deleted file mode 100644 index 0b189dff714f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest.py +++ /dev/null @@ -1,5300 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseEventarcRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -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}", -) - - -class EventarcRestInterceptor: - """Interceptor for Eventarc. - - 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 EventarcRestTransport. - - .. code-block:: python - class MyCustomEventarcInterceptor(EventarcRestInterceptor): - def pre_create_channel(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_channel(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_channel_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_channel_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_enrollment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_enrollment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_google_api_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_google_api_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_message_bus(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_message_bus(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_pipeline(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_pipeline(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_trigger(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_trigger(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_channel(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_channel(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_channel_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_channel_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_enrollment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_enrollment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_google_api_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_google_api_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_message_bus(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_message_bus(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_pipeline(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_pipeline(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_trigger(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_trigger(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_channel(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_channel(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_channel_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_channel_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_enrollment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_enrollment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_google_api_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_google_api_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_google_channel_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_google_channel_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_message_bus(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_message_bus(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_pipeline(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_pipeline(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_provider(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_provider(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_trigger(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_trigger(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_channel_connections(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_channel_connections(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_channels(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_channels(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_enrollments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_enrollments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_google_api_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_google_api_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_message_bus_enrollments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_message_bus_enrollments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_message_buses(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_message_buses(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_pipelines(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_pipelines(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_providers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_providers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_triggers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_triggers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_channel(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_channel(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_enrollment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_enrollment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_google_api_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_google_api_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_google_channel_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_google_channel_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_message_bus(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_message_bus(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_pipeline(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_pipeline(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_trigger(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_trigger(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EventarcRestTransport(interceptor=MyCustomEventarcInterceptor()) - client = EventarcClient(transport=transport) - - - """ - def pre_create_channel(self, request: eventarc.CreateChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_channel - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_channel - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_create_channel_connection(self, request: eventarc.CreateChannelConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateChannelConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_channel_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_channel_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_channel_connection - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_create_enrollment(self, request: eventarc.CreateEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateEnrollmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_enrollment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_enrollment - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_create_google_api_source(self, request: eventarc.CreateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_google_api_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_google_api_source - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_create_message_bus(self, request: eventarc.CreateMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateMessageBusRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_message_bus - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_message_bus - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_create_pipeline(self, request: eventarc.CreatePipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreatePipelineRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_pipeline - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_pipeline - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_create_trigger(self, request: eventarc.CreateTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.CreateTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_trigger - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_create_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_trigger - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_channel(self, request: eventarc.DeleteChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_channel - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_channel - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_channel_connection(self, request: eventarc.DeleteChannelConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteChannelConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_channel_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_channel_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_channel_connection - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_enrollment(self, request: eventarc.DeleteEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteEnrollmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_enrollment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_enrollment - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_google_api_source(self, request: eventarc.DeleteGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_google_api_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_google_api_source - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_message_bus(self, request: eventarc.DeleteMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteMessageBusRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_message_bus - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_message_bus - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_pipeline(self, request: eventarc.DeletePipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeletePipelineRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_pipeline - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_pipeline - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_trigger(self, request: eventarc.DeleteTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.DeleteTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_trigger - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_delete_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_trigger - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_channel(self, request: eventarc.GetChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_channel - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_channel(self, response: channel.Channel) -> channel.Channel: - """Post-rpc interceptor for get_channel - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_channel_connection(self, request: eventarc.GetChannelConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetChannelConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_channel_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_channel_connection(self, response: channel_connection.ChannelConnection) -> channel_connection.ChannelConnection: - """Post-rpc interceptor for get_channel_connection - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_enrollment(self, request: eventarc.GetEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetEnrollmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_enrollment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_enrollment(self, response: enrollment.Enrollment) -> enrollment.Enrollment: - """Post-rpc interceptor for get_enrollment - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_google_api_source(self, request: eventarc.GetGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_google_api_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_google_api_source(self, response: google_api_source.GoogleApiSource) -> google_api_source.GoogleApiSource: - """Post-rpc interceptor for get_google_api_source - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_google_channel_config(self, request: eventarc.GetGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_google_channel_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_google_channel_config(self, response: google_channel_config.GoogleChannelConfig) -> google_channel_config.GoogleChannelConfig: - """Post-rpc interceptor for get_google_channel_config - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_message_bus(self, request: eventarc.GetMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetMessageBusRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_message_bus - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_message_bus(self, response: message_bus.MessageBus) -> message_bus.MessageBus: - """Post-rpc interceptor for get_message_bus - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_pipeline(self, request: eventarc.GetPipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetPipelineRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_pipeline - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_pipeline(self, response: pipeline.Pipeline) -> pipeline.Pipeline: - """Post-rpc interceptor for get_pipeline - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_provider(self, request: eventarc.GetProviderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetProviderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_provider - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_provider(self, response: discovery.Provider) -> discovery.Provider: - """Post-rpc interceptor for get_provider - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_trigger(self, request: eventarc.GetTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.GetTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_trigger - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_get_trigger(self, response: trigger.Trigger) -> trigger.Trigger: - """Post-rpc interceptor for get_trigger - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_channel_connections(self, request: eventarc.ListChannelConnectionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListChannelConnectionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_channel_connections - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_channel_connections(self, response: eventarc.ListChannelConnectionsResponse) -> eventarc.ListChannelConnectionsResponse: - """Post-rpc interceptor for list_channel_connections - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_channels(self, request: eventarc.ListChannelsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListChannelsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_channels - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_channels(self, response: eventarc.ListChannelsResponse) -> eventarc.ListChannelsResponse: - """Post-rpc interceptor for list_channels - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_enrollments(self, request: eventarc.ListEnrollmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListEnrollmentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_enrollments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_enrollments(self, response: eventarc.ListEnrollmentsResponse) -> eventarc.ListEnrollmentsResponse: - """Post-rpc interceptor for list_enrollments - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_google_api_sources(self, request: eventarc.ListGoogleApiSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListGoogleApiSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_google_api_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_google_api_sources(self, response: eventarc.ListGoogleApiSourcesResponse) -> eventarc.ListGoogleApiSourcesResponse: - """Post-rpc interceptor for list_google_api_sources - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_message_bus_enrollments(self, request: eventarc.ListMessageBusEnrollmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListMessageBusEnrollmentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_message_bus_enrollments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_message_bus_enrollments(self, response: eventarc.ListMessageBusEnrollmentsResponse) -> eventarc.ListMessageBusEnrollmentsResponse: - """Post-rpc interceptor for list_message_bus_enrollments - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_message_buses(self, request: eventarc.ListMessageBusesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListMessageBusesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_message_buses - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_message_buses(self, response: eventarc.ListMessageBusesResponse) -> eventarc.ListMessageBusesResponse: - """Post-rpc interceptor for list_message_buses - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_pipelines(self, request: eventarc.ListPipelinesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListPipelinesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_pipelines - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_pipelines(self, response: eventarc.ListPipelinesResponse) -> eventarc.ListPipelinesResponse: - """Post-rpc interceptor for list_pipelines - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_providers(self, request: eventarc.ListProvidersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListProvidersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_providers - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_providers(self, response: eventarc.ListProvidersResponse) -> eventarc.ListProvidersResponse: - """Post-rpc interceptor for list_providers - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_triggers(self, request: eventarc.ListTriggersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.ListTriggersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_triggers - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_list_triggers(self, response: eventarc.ListTriggersResponse) -> eventarc.ListTriggersResponse: - """Post-rpc interceptor for list_triggers - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_channel(self, request: eventarc.UpdateChannelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_channel - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_channel - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_enrollment(self, request: eventarc.UpdateEnrollmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateEnrollmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_enrollment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_enrollment - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_google_api_source(self, request: eventarc.UpdateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_google_api_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_google_api_source - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_google_channel_config(self, request: eventarc.UpdateGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_google_channel_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_google_channel_config(self, response: gce_google_channel_config.GoogleChannelConfig) -> gce_google_channel_config.GoogleChannelConfig: - """Post-rpc interceptor for update_google_channel_config - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_message_bus(self, request: eventarc.UpdateMessageBusRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateMessageBusRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_message_bus - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_message_bus - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_pipeline(self, request: eventarc.UpdatePipelineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdatePipelineRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_pipeline - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_pipeline - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_update_trigger(self, request: eventarc.UpdateTriggerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[eventarc.UpdateTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_trigger - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc server. - """ - return request, metadata - - def post_update_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_trigger - - Override in a subclass to manipulate the response - after it is returned by the Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc 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, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc 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, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc 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, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Eventarc 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 Eventarc server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EventarcRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EventarcRestInterceptor - - -class EventarcRestTransport(_BaseEventarcRestTransport): - """REST backend synchronous transport for Eventarc. - - Eventarc allows users to subscribe to various events that are - provided by Google Cloud services and forward them to supported - destinations. - - This 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 = 'eventarc.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[EventarcRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'eventarc.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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - 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 EventarcRestInterceptor() - 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': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - '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 _CreateChannel(_BaseEventarcRestTransport._BaseCreateChannel, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreateChannel") - - @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: eventarc.CreateChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create channel method over HTTP. - - Args: - request (~.eventarc.CreateChannelRequest): - The request object. The request message for the - CreateChannel method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreateChannel._get_http_options() - request, metadata = self._interceptor.pre_create_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateChannel._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreateChannel._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateChannel._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreateChannel._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_channel(resp) - return resp - - class _CreateChannelConnection(_BaseEventarcRestTransport._BaseCreateChannelConnection, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreateChannelConnection") - - @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: eventarc.CreateChannelConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create channel connection method over HTTP. - - Args: - request (~.eventarc.CreateChannelConnectionRequest): - The request object. The request message for the - CreateChannelConnection method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_http_options() - request, metadata = self._interceptor.pre_create_channel_connection(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreateChannelConnection._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_channel_connection(resp) - return resp - - class _CreateEnrollment(_BaseEventarcRestTransport._BaseCreateEnrollment, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreateEnrollment") - - @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: eventarc.CreateEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create enrollment method over HTTP. - - Args: - request (~.eventarc.CreateEnrollmentRequest): - The request object. The request message for the - CreateEnrollment method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreateEnrollment._get_http_options() - request, metadata = self._interceptor.pre_create_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateEnrollment._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreateEnrollment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateEnrollment._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreateEnrollment._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_enrollment(resp) - return resp - - class _CreateGoogleApiSource(_BaseEventarcRestTransport._BaseCreateGoogleApiSource, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreateGoogleApiSource") - - @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: eventarc.CreateGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create google api source method over HTTP. - - Args: - request (~.eventarc.CreateGoogleApiSourceRequest): - The request object. The request message for the - CreateGoogleApiSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_http_options() - request, metadata = self._interceptor.pre_create_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreateGoogleApiSource._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_google_api_source(resp) - return resp - - class _CreateMessageBus(_BaseEventarcRestTransport._BaseCreateMessageBus, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreateMessageBus") - - @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: eventarc.CreateMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create message bus method over HTTP. - - Args: - request (~.eventarc.CreateMessageBusRequest): - The request object. The request message for the - CreateMessageBus method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreateMessageBus._get_http_options() - request, metadata = self._interceptor.pre_create_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateMessageBus._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreateMessageBus._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateMessageBus._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreateMessageBus._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_message_bus(resp) - return resp - - class _CreatePipeline(_BaseEventarcRestTransport._BaseCreatePipeline, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreatePipeline") - - @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: eventarc.CreatePipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create pipeline method over HTTP. - - Args: - request (~.eventarc.CreatePipelineRequest): - The request object. The request message for the - CreatePipeline method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreatePipeline._get_http_options() - request, metadata = self._interceptor.pre_create_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreatePipeline._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreatePipeline._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreatePipeline._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreatePipeline._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_pipeline(resp) - return resp - - class _CreateTrigger(_BaseEventarcRestTransport._BaseCreateTrigger, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.CreateTrigger") - - @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: eventarc.CreateTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create trigger method over HTTP. - - Args: - request (~.eventarc.CreateTriggerRequest): - The request object. The request message for the - CreateTrigger method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseCreateTrigger._get_http_options() - request, metadata = self._interceptor.pre_create_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateTrigger._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCreateTrigger._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateTrigger._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CreateTrigger._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_trigger(resp) - return resp - - class _DeleteChannel(_BaseEventarcRestTransport._BaseDeleteChannel, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeleteChannel") - - @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: eventarc.DeleteChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete channel method over HTTP. - - Args: - request (~.eventarc.DeleteChannelRequest): - The request object. The request message for the - DeleteChannel method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteChannel._get_http_options() - request, metadata = self._interceptor.pre_delete_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannel._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteChannel._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeleteChannel._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_channel(resp) - return resp - - class _DeleteChannelConnection(_BaseEventarcRestTransport._BaseDeleteChannelConnection, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeleteChannelConnection") - - @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: eventarc.DeleteChannelConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete channel connection method over HTTP. - - Args: - request (~.eventarc.DeleteChannelConnectionRequest): - The request object. The request message for the - DeleteChannelConnection method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_http_options() - request, metadata = self._interceptor.pre_delete_channel_connection(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeleteChannelConnection._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_channel_connection(resp) - return resp - - class _DeleteEnrollment(_BaseEventarcRestTransport._BaseDeleteEnrollment, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeleteEnrollment") - - @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: eventarc.DeleteEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete enrollment method over HTTP. - - Args: - request (~.eventarc.DeleteEnrollmentRequest): - The request object. The request message for the - DeleteEnrollment method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_http_options() - request, metadata = self._interceptor.pre_delete_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeleteEnrollment._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_enrollment(resp) - return resp - - class _DeleteGoogleApiSource(_BaseEventarcRestTransport._BaseDeleteGoogleApiSource, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeleteGoogleApiSource") - - @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: eventarc.DeleteGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete google api source method over HTTP. - - Args: - request (~.eventarc.DeleteGoogleApiSourceRequest): - The request object. The request message for the - DeleteGoogleApiSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_http_options() - request, metadata = self._interceptor.pre_delete_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeleteGoogleApiSource._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_google_api_source(resp) - return resp - - class _DeleteMessageBus(_BaseEventarcRestTransport._BaseDeleteMessageBus, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeleteMessageBus") - - @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: eventarc.DeleteMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete message bus method over HTTP. - - Args: - request (~.eventarc.DeleteMessageBusRequest): - The request object. The request message for the - DeleteMessageBus method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_http_options() - request, metadata = self._interceptor.pre_delete_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeleteMessageBus._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_message_bus(resp) - return resp - - class _DeletePipeline(_BaseEventarcRestTransport._BaseDeletePipeline, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeletePipeline") - - @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: eventarc.DeletePipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete pipeline method over HTTP. - - Args: - request (~.eventarc.DeletePipelineRequest): - The request object. The request message for the - DeletePipeline method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeletePipeline._get_http_options() - request, metadata = self._interceptor.pre_delete_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeletePipeline._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeletePipeline._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeletePipeline._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_pipeline(resp) - return resp - - class _DeleteTrigger(_BaseEventarcRestTransport._BaseDeleteTrigger, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.DeleteTrigger") - - @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: eventarc.DeleteTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete trigger method over HTTP. - - Args: - request (~.eventarc.DeleteTriggerRequest): - The request object. The request message for the - DeleteTrigger method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteTrigger._get_http_options() - request, metadata = self._interceptor.pre_delete_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteTrigger._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteTrigger._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._DeleteTrigger._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_trigger(resp) - return resp - - class _GetChannel(_BaseEventarcRestTransport._BaseGetChannel, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetChannel") - - @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: eventarc.GetChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> channel.Channel: - r"""Call the get channel method over HTTP. - - Args: - request (~.eventarc.GetChannelRequest): - The request object. The request message for the - GetChannel method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.channel.Channel: - A representation of the Channel - resource. A Channel is a resource on - which event providers publish their - events. The published events are - delivered through the transport - associated with the channel. Note that a - channel is associated with exactly one - event provider. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetChannel._get_http_options() - request, metadata = self._interceptor.pre_get_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetChannel._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetChannel._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetChannel._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 = channel.Channel() - pb_resp = channel.Channel.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_channel(resp) - return resp - - class _GetChannelConnection(_BaseEventarcRestTransport._BaseGetChannelConnection, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetChannelConnection") - - @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: eventarc.GetChannelConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> channel_connection.ChannelConnection: - r"""Call the get channel connection method over HTTP. - - Args: - request (~.eventarc.GetChannelConnectionRequest): - The request object. The request message for the - GetChannelConnection method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.channel_connection.ChannelConnection: - A representation of the - ChannelConnection resource. A - ChannelConnection is a resource which - event providers create during the - activation process to establish a - connection between the provider and the - subscriber channel. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetChannelConnection._get_http_options() - request, metadata = self._interceptor.pre_get_channel_connection(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetChannelConnection._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetChannelConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetChannelConnection._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 = channel_connection.ChannelConnection() - pb_resp = channel_connection.ChannelConnection.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_channel_connection(resp) - return resp - - class _GetEnrollment(_BaseEventarcRestTransport._BaseGetEnrollment, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetEnrollment") - - @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: eventarc.GetEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> enrollment.Enrollment: - r"""Call the get enrollment method over HTTP. - - Args: - request (~.eventarc.GetEnrollmentRequest): - The request object. The request message for the - GetEnrollment method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.enrollment.Enrollment: - An enrollment represents a - subscription for messages on a - particular message bus. It defines a - matching criteria for messages on the - bus and the subscriber endpoint where - matched messages should be delivered. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetEnrollment._get_http_options() - request, metadata = self._interceptor.pre_get_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetEnrollment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetEnrollment._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetEnrollment._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 = enrollment.Enrollment() - pb_resp = enrollment.Enrollment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_enrollment(resp) - return resp - - class _GetGoogleApiSource(_BaseEventarcRestTransport._BaseGetGoogleApiSource, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetGoogleApiSource") - - @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: eventarc.GetGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> google_api_source.GoogleApiSource: - r"""Call the get google api source method over HTTP. - - Args: - request (~.eventarc.GetGoogleApiSourceRequest): - The request object. The request message for the - GetGoogleApiSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.google_api_source.GoogleApiSource: - A GoogleApiSource represents a - subscription of 1P events from a - MessageBus. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_http_options() - request, metadata = self._interceptor.pre_get_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetGoogleApiSource._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 = google_api_source.GoogleApiSource() - pb_resp = google_api_source.GoogleApiSource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_google_api_source(resp) - return resp - - class _GetGoogleChannelConfig(_BaseEventarcRestTransport._BaseGetGoogleChannelConfig, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetGoogleChannelConfig") - - @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: eventarc.GetGoogleChannelConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> google_channel_config.GoogleChannelConfig: - r"""Call the get google channel config method over HTTP. - - Args: - request (~.eventarc.GetGoogleChannelConfigRequest): - The request object. The request message for the - GetGoogleChannelConfig method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.google_channel_config.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_http_options() - request, metadata = self._interceptor.pre_get_google_channel_config(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetGoogleChannelConfig._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 = google_channel_config.GoogleChannelConfig() - pb_resp = google_channel_config.GoogleChannelConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_google_channel_config(resp) - return resp - - class _GetMessageBus(_BaseEventarcRestTransport._BaseGetMessageBus, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetMessageBus") - - @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: eventarc.GetMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> message_bus.MessageBus: - r"""Call the get message bus method over HTTP. - - Args: - request (~.eventarc.GetMessageBusRequest): - The request object. The request message for the - GetMessageBus method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.message_bus.MessageBus: - MessageBus for the messages flowing - through the system. The admin has - visibility and control over the messages - being published and consumed and can - restrict publishers and subscribers to - only a subset of data available in the - system by defining authorization - policies. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetMessageBus._get_http_options() - request, metadata = self._interceptor.pre_get_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetMessageBus._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetMessageBus._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetMessageBus._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 = message_bus.MessageBus() - pb_resp = message_bus.MessageBus.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_message_bus(resp) - return resp - - class _GetPipeline(_BaseEventarcRestTransport._BaseGetPipeline, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetPipeline") - - @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: eventarc.GetPipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pipeline.Pipeline: - r"""Call the get pipeline method over HTTP. - - Args: - request (~.eventarc.GetPipelineRequest): - The request object. The request message for the - GetPipeline method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pipeline.Pipeline: - A representation of the Pipeline - resource. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetPipeline._get_http_options() - request, metadata = self._interceptor.pre_get_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetPipeline._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetPipeline._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetPipeline._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 = pipeline.Pipeline() - pb_resp = pipeline.Pipeline.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_pipeline(resp) - return resp - - class _GetProvider(_BaseEventarcRestTransport._BaseGetProvider, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetProvider") - - @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: eventarc.GetProviderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> discovery.Provider: - r"""Call the get provider method over HTTP. - - Args: - request (~.eventarc.GetProviderRequest): - The request object. The request message for the - GetProvider method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.discovery.Provider: - A representation of the Provider - resource. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetProvider._get_http_options() - request, metadata = self._interceptor.pre_get_provider(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetProvider._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetProvider._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetProvider._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 = discovery.Provider() - pb_resp = discovery.Provider.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_provider(resp) - return resp - - class _GetTrigger(_BaseEventarcRestTransport._BaseGetTrigger, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.GetTrigger") - - @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: eventarc.GetTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> trigger.Trigger: - r"""Call the get trigger method over HTTP. - - Args: - request (~.eventarc.GetTriggerRequest): - The request object. The request message for the - GetTrigger method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.trigger.Trigger: - A representation of the trigger - resource. - - """ - - http_options = _BaseEventarcRestTransport._BaseGetTrigger._get_http_options() - request, metadata = self._interceptor.pre_get_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetTrigger._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetTrigger._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._GetTrigger._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 = trigger.Trigger() - pb_resp = trigger.Trigger.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_trigger(resp) - return resp - - class _ListChannelConnections(_BaseEventarcRestTransport._BaseListChannelConnections, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListChannelConnections") - - @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: eventarc.ListChannelConnectionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListChannelConnectionsResponse: - r"""Call the list channel connections method over HTTP. - - Args: - request (~.eventarc.ListChannelConnectionsRequest): - The request object. The request message for the - ListChannelConnections method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListChannelConnectionsResponse: - The response message for the ``ListChannelConnections`` - method. - - """ - - http_options = _BaseEventarcRestTransport._BaseListChannelConnections._get_http_options() - request, metadata = self._interceptor.pre_list_channel_connections(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListChannelConnections._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListChannelConnections._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListChannelConnections._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 = eventarc.ListChannelConnectionsResponse() - pb_resp = eventarc.ListChannelConnectionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_channel_connections(resp) - return resp - - class _ListChannels(_BaseEventarcRestTransport._BaseListChannels, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListChannels") - - @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: eventarc.ListChannelsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListChannelsResponse: - r"""Call the list channels method over HTTP. - - Args: - request (~.eventarc.ListChannelsRequest): - The request object. The request message for the - ListChannels method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListChannelsResponse: - The response message for the ``ListChannels`` method. - """ - - http_options = _BaseEventarcRestTransport._BaseListChannels._get_http_options() - request, metadata = self._interceptor.pre_list_channels(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListChannels._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListChannels._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListChannels._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 = eventarc.ListChannelsResponse() - pb_resp = eventarc.ListChannelsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_channels(resp) - return resp - - class _ListEnrollments(_BaseEventarcRestTransport._BaseListEnrollments, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListEnrollments") - - @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: eventarc.ListEnrollmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListEnrollmentsResponse: - r"""Call the list enrollments method over HTTP. - - Args: - request (~.eventarc.ListEnrollmentsRequest): - The request object. The request message for the - ListEnrollments method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListEnrollmentsResponse: - The response message for the ``ListEnrollments`` method. - """ - - http_options = _BaseEventarcRestTransport._BaseListEnrollments._get_http_options() - request, metadata = self._interceptor.pre_list_enrollments(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListEnrollments._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListEnrollments._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListEnrollments._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 = eventarc.ListEnrollmentsResponse() - pb_resp = eventarc.ListEnrollmentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_enrollments(resp) - return resp - - class _ListGoogleApiSources(_BaseEventarcRestTransport._BaseListGoogleApiSources, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListGoogleApiSources") - - @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: eventarc.ListGoogleApiSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListGoogleApiSourcesResponse: - r"""Call the list google api sources method over HTTP. - - Args: - request (~.eventarc.ListGoogleApiSourcesRequest): - The request object. The request message for the - ListGoogleApiSources method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListGoogleApiSourcesResponse: - The response message for the ``ListGoogleApiSources`` - method. - - """ - - http_options = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_http_options() - request, metadata = self._interceptor.pre_list_google_api_sources(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListGoogleApiSources._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 = eventarc.ListGoogleApiSourcesResponse() - pb_resp = eventarc.ListGoogleApiSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_google_api_sources(resp) - return resp - - class _ListMessageBusEnrollments(_BaseEventarcRestTransport._BaseListMessageBusEnrollments, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListMessageBusEnrollments") - - @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: eventarc.ListMessageBusEnrollmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListMessageBusEnrollmentsResponse: - r"""Call the list message bus - enrollments method over HTTP. - - Args: - request (~.eventarc.ListMessageBusEnrollmentsRequest): - The request object. The request message for the - ``ListMessageBusEnrollments`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListMessageBusEnrollmentsResponse: - The response message for the - ``ListMessageBusEnrollments`` method.\` - - """ - - http_options = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_http_options() - request, metadata = self._interceptor.pre_list_message_bus_enrollments(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListMessageBusEnrollments._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 = eventarc.ListMessageBusEnrollmentsResponse() - pb_resp = eventarc.ListMessageBusEnrollmentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_message_bus_enrollments(resp) - return resp - - class _ListMessageBuses(_BaseEventarcRestTransport._BaseListMessageBuses, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListMessageBuses") - - @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: eventarc.ListMessageBusesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListMessageBusesResponse: - r"""Call the list message buses method over HTTP. - - Args: - request (~.eventarc.ListMessageBusesRequest): - The request object. The request message for the - ListMessageBuses method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListMessageBusesResponse: - The response message for the ``ListMessageBuses`` - method. - - """ - - http_options = _BaseEventarcRestTransport._BaseListMessageBuses._get_http_options() - request, metadata = self._interceptor.pre_list_message_buses(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListMessageBuses._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListMessageBuses._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListMessageBuses._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 = eventarc.ListMessageBusesResponse() - pb_resp = eventarc.ListMessageBusesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_message_buses(resp) - return resp - - class _ListPipelines(_BaseEventarcRestTransport._BaseListPipelines, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListPipelines") - - @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: eventarc.ListPipelinesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListPipelinesResponse: - r"""Call the list pipelines method over HTTP. - - Args: - request (~.eventarc.ListPipelinesRequest): - The request object. The request message for the - ListPipelines method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListPipelinesResponse: - The response message for the - ListPipelines method. - - """ - - http_options = _BaseEventarcRestTransport._BaseListPipelines._get_http_options() - request, metadata = self._interceptor.pre_list_pipelines(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListPipelines._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListPipelines._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListPipelines._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 = eventarc.ListPipelinesResponse() - pb_resp = eventarc.ListPipelinesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_pipelines(resp) - return resp - - class _ListProviders(_BaseEventarcRestTransport._BaseListProviders, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListProviders") - - @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: eventarc.ListProvidersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListProvidersResponse: - r"""Call the list providers method over HTTP. - - Args: - request (~.eventarc.ListProvidersRequest): - The request object. The request message for the - ListProviders method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListProvidersResponse: - The response message for the ``ListProviders`` method. - """ - - http_options = _BaseEventarcRestTransport._BaseListProviders._get_http_options() - request, metadata = self._interceptor.pre_list_providers(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListProviders._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListProviders._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListProviders._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 = eventarc.ListProvidersResponse() - pb_resp = eventarc.ListProvidersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_providers(resp) - return resp - - class _ListTriggers(_BaseEventarcRestTransport._BaseListTriggers, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.ListTriggers") - - @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: eventarc.ListTriggersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> eventarc.ListTriggersResponse: - r"""Call the list triggers method over HTTP. - - Args: - request (~.eventarc.ListTriggersRequest): - The request object. The request message for the - ListTriggers method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.eventarc.ListTriggersResponse: - The response message for the ``ListTriggers`` method. - """ - - http_options = _BaseEventarcRestTransport._BaseListTriggers._get_http_options() - request, metadata = self._interceptor.pre_list_triggers(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListTriggers._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListTriggers._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._ListTriggers._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 = eventarc.ListTriggersResponse() - pb_resp = eventarc.ListTriggersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_triggers(resp) - return resp - - class _UpdateChannel(_BaseEventarcRestTransport._BaseUpdateChannel, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdateChannel") - - @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: eventarc.UpdateChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update channel method over HTTP. - - Args: - request (~.eventarc.UpdateChannelRequest): - The request object. The request message for the - UpdateChannel method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdateChannel._get_http_options() - request, metadata = self._interceptor.pre_update_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateChannel._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdateChannel._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateChannel._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdateChannel._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_update_channel(resp) - return resp - - class _UpdateEnrollment(_BaseEventarcRestTransport._BaseUpdateEnrollment, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdateEnrollment") - - @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: eventarc.UpdateEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update enrollment method over HTTP. - - Args: - request (~.eventarc.UpdateEnrollmentRequest): - The request object. The request message for the - UpdateEnrollment method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_http_options() - request, metadata = self._interceptor.pre_update_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdateEnrollment._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_update_enrollment(resp) - return resp - - class _UpdateGoogleApiSource(_BaseEventarcRestTransport._BaseUpdateGoogleApiSource, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdateGoogleApiSource") - - @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: eventarc.UpdateGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update google api source method over HTTP. - - Args: - request (~.eventarc.UpdateGoogleApiSourceRequest): - The request object. The request message for the - UpdateGoogleApiSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_http_options() - request, metadata = self._interceptor.pre_update_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdateGoogleApiSource._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_update_google_api_source(resp) - return resp - - class _UpdateGoogleChannelConfig(_BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdateGoogleChannelConfig") - - @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: eventarc.UpdateGoogleChannelConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gce_google_channel_config.GoogleChannelConfig: - r"""Call the update google channel - config method over HTTP. - - Args: - request (~.eventarc.UpdateGoogleChannelConfigRequest): - The request object. The request message for the - UpdateGoogleChannelConfig method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gce_google_channel_config.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_http_options() - request, metadata = self._interceptor.pre_update_google_channel_config(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdateGoogleChannelConfig._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 = gce_google_channel_config.GoogleChannelConfig() - pb_resp = gce_google_channel_config.GoogleChannelConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_google_channel_config(resp) - return resp - - class _UpdateMessageBus(_BaseEventarcRestTransport._BaseUpdateMessageBus, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdateMessageBus") - - @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: eventarc.UpdateMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update message bus method over HTTP. - - Args: - request (~.eventarc.UpdateMessageBusRequest): - The request object. The request message for the - UpdateMessageBus method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_http_options() - request, metadata = self._interceptor.pre_update_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdateMessageBus._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_update_message_bus(resp) - return resp - - class _UpdatePipeline(_BaseEventarcRestTransport._BaseUpdatePipeline, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdatePipeline") - - @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: eventarc.UpdatePipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update pipeline method over HTTP. - - Args: - request (~.eventarc.UpdatePipelineRequest): - The request object. The request message for the - UpdatePipeline method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdatePipeline._get_http_options() - request, metadata = self._interceptor.pre_update_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdatePipeline._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdatePipeline._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdatePipeline._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdatePipeline._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_update_pipeline(resp) - return resp - - class _UpdateTrigger(_BaseEventarcRestTransport._BaseUpdateTrigger, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.UpdateTrigger") - - @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: eventarc.UpdateTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update trigger method over HTTP. - - Args: - request (~.eventarc.UpdateTriggerRequest): - The request object. The request message for the - UpdateTrigger method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEventarcRestTransport._BaseUpdateTrigger._get_http_options() - request, metadata = self._interceptor.pre_update_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateTrigger._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseUpdateTrigger._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateTrigger._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._UpdateTrigger._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_update_trigger(resp) - return resp - - @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - 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._CreateChannel(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - 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._CreateChannelConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - 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._CreateEnrollment(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - 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._CreateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - 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._CreateMessageBus(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - 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._CreatePipeline(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - 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._CreateTrigger(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - 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._DeleteChannel(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - 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._DeleteChannelConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - 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._DeleteEnrollment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - 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._DeleteGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - 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._DeleteMessageBus(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - 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._DeletePipeline(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - 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._DeleteTrigger(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - channel.Channel]: - # 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._GetChannel(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - channel_connection.ChannelConnection]: - # 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._GetChannelConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - enrollment.Enrollment]: - # 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._GetEnrollment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - google_api_source.GoogleApiSource]: - # 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._GetGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - google_channel_config.GoogleChannelConfig]: - # 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._GetGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - message_bus.MessageBus]: - # 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._GetMessageBus(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - pipeline.Pipeline]: - # 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._GetPipeline(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - discovery.Provider]: - # 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._GetProvider(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - trigger.Trigger]: - # 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._GetTrigger(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - eventarc.ListChannelConnectionsResponse]: - # 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._ListChannelConnections(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - eventarc.ListChannelsResponse]: - # 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._ListChannels(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - eventarc.ListEnrollmentsResponse]: - # 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._ListEnrollments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - eventarc.ListGoogleApiSourcesResponse]: - # 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._ListGoogleApiSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - eventarc.ListMessageBusEnrollmentsResponse]: - # 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._ListMessageBusEnrollments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - eventarc.ListMessageBusesResponse]: - # 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._ListMessageBuses(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - eventarc.ListPipelinesResponse]: - # 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._ListPipelines(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - eventarc.ListProvidersResponse]: - # 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._ListProviders(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - eventarc.ListTriggersResponse]: - # 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._ListTriggers(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - 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._UpdateChannel(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - 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._UpdateEnrollment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - 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._UpdateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - gce_google_channel_config.GoogleChannelConfig]: - # 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._UpdateGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - 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._UpdateMessageBus(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - 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._UpdatePipeline(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - 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._UpdateTrigger(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(_BaseEventarcRestTransport._BaseGetLocation, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseEventarcRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseEventarcRestTransport._BaseListLocations, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseEventarcRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseEventarcRestTransport._BaseGetIamPolicy, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseEventarcRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseEventarcRestTransport._BaseSetIamPolicy, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseEventarcRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseEventarcRestTransport._BaseTestIamPermissions, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseEventarcRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseEventarcRestTransport._BaseCancelOperation, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options = _BaseEventarcRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseEventarcRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._CancelOperation._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 self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseEventarcRestTransport._BaseDeleteOperation, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options = _BaseEventarcRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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(_BaseEventarcRestTransport._BaseGetOperation, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseEventarcRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseEventarcRestTransport._BaseListOperations, EventarcRestStub): - def __hash__(self): - return hash("EventarcRestTransport.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, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseEventarcRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = EventarcRestTransport._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) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EventarcRestTransport', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py deleted file mode 100644 index 09c44e75071f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py +++ /dev/null @@ -1,1996 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import EventarcTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseEventarcRestTransport(EventarcTransport): - """Base REST backend transport for Eventarc. - - 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 = 'eventarc.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: 'eventarc.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 _BaseCreateChannel: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "channelId" : "", } - - @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/*}/channels', - 'body': 'channel', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateChannelRequest.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(_BaseEventarcRestTransport._BaseCreateChannel._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateChannelConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "channelConnectionId" : "", } - - @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/*}/channelConnections', - 'body': 'channel_connection', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateChannelConnectionRequest.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(_BaseEventarcRestTransport._BaseCreateChannelConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateEnrollment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "enrollmentId" : "", } - - @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/*}/enrollments', - 'body': 'enrollment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateEnrollmentRequest.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(_BaseEventarcRestTransport._BaseCreateEnrollment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateGoogleApiSource: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "googleApiSourceId" : "", } - - @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/*}/googleApiSources', - 'body': 'google_api_source', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateMessageBus: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "messageBusId" : "", } - - @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/*}/messageBuses', - 'body': 'message_bus', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateMessageBusRequest.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(_BaseEventarcRestTransport._BaseCreateMessageBus._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreatePipeline: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "pipelineId" : "", } - - @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/*}/pipelines', - 'body': 'pipeline', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreatePipelineRequest.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(_BaseEventarcRestTransport._BaseCreatePipeline._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateTrigger: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "triggerId" : "", } - - @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/*}/triggers', - 'body': 'trigger', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateTriggerRequest.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(_BaseEventarcRestTransport._BaseCreateTrigger._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteChannel: - 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/*/channels/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteChannelRequest.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(_BaseEventarcRestTransport._BaseDeleteChannel._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteChannelConnection: - 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/*/channelConnections/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteChannelConnectionRequest.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(_BaseEventarcRestTransport._BaseDeleteChannelConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteEnrollment: - 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/*/enrollments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteEnrollmentRequest.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(_BaseEventarcRestTransport._BaseDeleteEnrollment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteGoogleApiSource: - 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/*/googleApiSources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteMessageBus: - 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/*/messageBuses/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteMessageBusRequest.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(_BaseEventarcRestTransport._BaseDeleteMessageBus._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeletePipeline: - 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/*/pipelines/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeletePipelineRequest.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(_BaseEventarcRestTransport._BaseDeletePipeline._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteTrigger: - 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/*/triggers/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteTriggerRequest.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(_BaseEventarcRestTransport._BaseDeleteTrigger._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetChannel: - 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/*/channels/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetChannelRequest.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(_BaseEventarcRestTransport._BaseGetChannel._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetChannelConnection: - 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/*/channelConnections/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetChannelConnectionRequest.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(_BaseEventarcRestTransport._BaseGetChannelConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetEnrollment: - 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/*/enrollments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetEnrollmentRequest.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(_BaseEventarcRestTransport._BaseGetEnrollment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetGoogleApiSource: - 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/*/googleApiSources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseGetGoogleApiSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetGoogleChannelConfig: - 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/*/googleChannelConfig}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetGoogleChannelConfigRequest.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(_BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetMessageBus: - 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/*/messageBuses/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetMessageBusRequest.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(_BaseEventarcRestTransport._BaseGetMessageBus._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPipeline: - 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/*/pipelines/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetPipelineRequest.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(_BaseEventarcRestTransport._BaseGetPipeline._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetProvider: - 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/*/providers/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetProviderRequest.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(_BaseEventarcRestTransport._BaseGetProvider._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetTrigger: - 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/*/triggers/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetTriggerRequest.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(_BaseEventarcRestTransport._BaseGetTrigger._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListChannelConnections: - 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/*}/channelConnections', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListChannelConnectionsRequest.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(_BaseEventarcRestTransport._BaseListChannelConnections._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListChannels: - 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/*}/channels', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListChannelsRequest.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(_BaseEventarcRestTransport._BaseListChannels._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListEnrollments: - 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/*}/enrollments', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListEnrollmentsRequest.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(_BaseEventarcRestTransport._BaseListEnrollments._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListGoogleApiSources: - 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/*}/googleApiSources', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListGoogleApiSourcesRequest.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(_BaseEventarcRestTransport._BaseListGoogleApiSources._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListMessageBusEnrollments: - 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/*/messageBuses/*}:listEnrollments', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListMessageBusEnrollmentsRequest.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(_BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListMessageBuses: - 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/*}/messageBuses', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListMessageBusesRequest.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(_BaseEventarcRestTransport._BaseListMessageBuses._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListPipelines: - 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/*}/pipelines', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListPipelinesRequest.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(_BaseEventarcRestTransport._BaseListPipelines._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListProviders: - 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/*}/providers', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListProvidersRequest.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(_BaseEventarcRestTransport._BaseListProviders._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListTriggers: - 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/*}/triggers', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListTriggersRequest.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(_BaseEventarcRestTransport._BaseListTriggers._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateChannel: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{channel.name=projects/*/locations/*/channels/*}', - 'body': 'channel', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateChannelRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateEnrollment: - 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': '/v1/{enrollment.name=projects/*/locations/*/enrollments/*}', - 'body': 'enrollment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateEnrollmentRequest.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(_BaseEventarcRestTransport._BaseUpdateEnrollment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateGoogleApiSource: - 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': '/v1/{google_api_source.name=projects/*/locations/*/googleApiSources/*}', - 'body': 'google_api_source', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateGoogleApiSourceRequest.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(_BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateGoogleChannelConfig: - 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': '/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}', - 'body': 'google_channel_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateGoogleChannelConfigRequest.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(_BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateMessageBus: - 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': '/v1/{message_bus.name=projects/*/locations/*/messageBuses/*}', - 'body': 'message_bus', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateMessageBusRequest.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(_BaseEventarcRestTransport._BaseUpdateMessageBus._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdatePipeline: - 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': '/v1/{pipeline.name=projects/*/locations/*/pipelines/*}', - 'body': 'pipeline', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdatePipelineRequest.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(_BaseEventarcRestTransport._BaseUpdatePipeline._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateTrigger: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{trigger.name=projects/*/locations/*/triggers/*}', - 'body': 'trigger', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateTriggerRequest.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["$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/*/triggers/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/channels/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/channelConnections/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/messageBuses/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/enrollments/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/pipelines/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/googleApiSources/*}: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/*/triggers/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/channels/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/channelConnections/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/messageBuses/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/enrollments/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/pipelines/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/googleApiSources/*}: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/*/triggers/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/channels/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/channelConnections/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/messageBuses/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/enrollments/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/pipelines/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/googleApiSources/*}: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 _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': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - '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 _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': '/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 - - 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 - - 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': '/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__=( - '_BaseEventarcRestTransport', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py deleted file mode 100644 index 010c3974f234..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/__init__.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .channel import ( - Channel, -) -from .channel_connection import ( - ChannelConnection, -) -from .discovery import ( - EventType, - FilteringAttribute, - Provider, -) -from .enrollment import ( - Enrollment, -) -from .eventarc import ( - CreateChannelConnectionRequest, - CreateChannelRequest, - CreateEnrollmentRequest, - CreateGoogleApiSourceRequest, - CreateMessageBusRequest, - CreatePipelineRequest, - CreateTriggerRequest, - DeleteChannelConnectionRequest, - DeleteChannelRequest, - DeleteEnrollmentRequest, - DeleteGoogleApiSourceRequest, - DeleteMessageBusRequest, - DeletePipelineRequest, - DeleteTriggerRequest, - GetChannelConnectionRequest, - GetChannelRequest, - GetEnrollmentRequest, - GetGoogleApiSourceRequest, - GetGoogleChannelConfigRequest, - GetMessageBusRequest, - GetPipelineRequest, - GetProviderRequest, - GetTriggerRequest, - ListChannelConnectionsRequest, - ListChannelConnectionsResponse, - ListChannelsRequest, - ListChannelsResponse, - ListEnrollmentsRequest, - ListEnrollmentsResponse, - ListGoogleApiSourcesRequest, - ListGoogleApiSourcesResponse, - ListMessageBusEnrollmentsRequest, - ListMessageBusEnrollmentsResponse, - ListMessageBusesRequest, - ListMessageBusesResponse, - ListPipelinesRequest, - ListPipelinesResponse, - ListProvidersRequest, - ListProvidersResponse, - ListTriggersRequest, - ListTriggersResponse, - OperationMetadata, - UpdateChannelRequest, - UpdateEnrollmentRequest, - UpdateGoogleApiSourceRequest, - UpdateGoogleChannelConfigRequest, - UpdateMessageBusRequest, - UpdatePipelineRequest, - UpdateTriggerRequest, -) -from .google_api_source import ( - GoogleApiSource, -) -from .google_channel_config import ( - GoogleChannelConfig, -) -from .logging_config import ( - LoggingConfig, -) -from .message_bus import ( - MessageBus, -) -from .network_config import ( - NetworkConfig, -) -from .pipeline import ( - Pipeline, -) -from .trigger import ( - CloudRun, - Destination, - EventFilter, - GKE, - HttpEndpoint, - Pubsub, - StateCondition, - Transport, - Trigger, -) - -__all__ = ( - 'Channel', - 'ChannelConnection', - 'EventType', - 'FilteringAttribute', - 'Provider', - 'Enrollment', - 'CreateChannelConnectionRequest', - 'CreateChannelRequest', - 'CreateEnrollmentRequest', - 'CreateGoogleApiSourceRequest', - 'CreateMessageBusRequest', - 'CreatePipelineRequest', - 'CreateTriggerRequest', - 'DeleteChannelConnectionRequest', - 'DeleteChannelRequest', - 'DeleteEnrollmentRequest', - 'DeleteGoogleApiSourceRequest', - 'DeleteMessageBusRequest', - 'DeletePipelineRequest', - 'DeleteTriggerRequest', - 'GetChannelConnectionRequest', - 'GetChannelRequest', - 'GetEnrollmentRequest', - 'GetGoogleApiSourceRequest', - 'GetGoogleChannelConfigRequest', - 'GetMessageBusRequest', - 'GetPipelineRequest', - 'GetProviderRequest', - 'GetTriggerRequest', - 'ListChannelConnectionsRequest', - 'ListChannelConnectionsResponse', - 'ListChannelsRequest', - 'ListChannelsResponse', - 'ListEnrollmentsRequest', - 'ListEnrollmentsResponse', - 'ListGoogleApiSourcesRequest', - 'ListGoogleApiSourcesResponse', - 'ListMessageBusEnrollmentsRequest', - 'ListMessageBusEnrollmentsResponse', - 'ListMessageBusesRequest', - 'ListMessageBusesResponse', - 'ListPipelinesRequest', - 'ListPipelinesResponse', - 'ListProvidersRequest', - 'ListProvidersResponse', - 'ListTriggersRequest', - 'ListTriggersResponse', - 'OperationMetadata', - 'UpdateChannelRequest', - 'UpdateEnrollmentRequest', - 'UpdateGoogleApiSourceRequest', - 'UpdateGoogleChannelConfigRequest', - 'UpdateMessageBusRequest', - 'UpdatePipelineRequest', - 'UpdateTriggerRequest', - 'GoogleApiSource', - 'GoogleChannelConfig', - 'LoggingConfig', - 'MessageBus', - 'NetworkConfig', - 'Pipeline', - 'CloudRun', - 'Destination', - 'EventFilter', - 'GKE', - 'HttpEndpoint', - 'Pubsub', - 'StateCondition', - 'Transport', - 'Trigger', -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py deleted file mode 100644 index 811438b887b6..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'Channel', - }, -) - - -class Channel(proto.Message): - r"""A representation of the Channel resource. - A Channel is a resource on which event providers publish their - events. The published events are delivered through the transport - associated with the channel. Note that a channel is associated - with exactly one event provider. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. The resource name of the channel. Must be unique - within the location on the project and must be in - ``projects/{project}/locations/{location}/channels/{channel_id}`` - format. - uid (str): - Output only. Server assigned unique - identifier for the channel. The value is a UUID4 - string and guaranteed to remain unchanged until - the resource is deleted. - 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. - provider (str): - The name of the event provider (e.g. Eventarc SaaS partner) - associated with the channel. This provider will be granted - permissions to publish events to the channel. Format: - ``projects/{project}/locations/{location}/providers/{provider_id}``. - pubsub_topic (str): - Output only. The name of the Pub/Sub topic created and - managed by Eventarc system as a transport for the event - delivery. Format: ``projects/{project}/topics/{topic_id}``. - - This field is a member of `oneof`_ ``transport``. - state (google.cloud.eventarc_v1.types.Channel.State): - Output only. The state of a Channel. - activation_token (str): - Output only. The activation token for the - channel. The token must be used by the provider - to register the channel for publishing. - crypto_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt their event data. - - It must match the pattern - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - satisfies_pzs (bool): - Output only. Whether or not this Channel - satisfies the requirements of physical zone - separation - """ - class State(proto.Enum): - r"""State lists all the possible states of a Channel - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - PENDING (1): - The PENDING state indicates that a Channel - has been created successfully and there is a new - activation token available for the subscriber to - use to convey the Channel to the provider in - order to create a Connection. - ACTIVE (2): - The ACTIVE state indicates that a Channel has - been successfully connected with the event - provider. An ACTIVE Channel is ready to receive - and route events from the event provider. - INACTIVE (3): - The INACTIVE state indicates that the Channel - cannot receive events permanently. There are two - possible cases this state can happen: - - 1. The SaaS provider disconnected from this - Channel. - 2. The Channel activation token has expired but - the SaaS provider wasn't connected. - - To re-establish a Connection with a provider, - the subscriber should create a new Channel and - give it to the provider. - """ - STATE_UNSPECIFIED = 0 - PENDING = 1 - ACTIVE = 2 - INACTIVE = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uid: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - provider: str = proto.Field( - proto.STRING, - number=7, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=8, - oneof='transport', - ) - state: State = proto.Field( - proto.ENUM, - number=9, - enum=State, - ) - activation_token: str = proto.Field( - proto.STRING, - number=10, - ) - crypto_key_name: str = proto.Field( - proto.STRING, - number=11, - ) - satisfies_pzs: bool = proto.Field( - proto.BOOL, - number=12, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py deleted file mode 100644 index 59d79edf4331..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/channel_connection.py +++ /dev/null @@ -1,92 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'ChannelConnection', - }, -) - - -class ChannelConnection(proto.Message): - r"""A representation of the ChannelConnection resource. - A ChannelConnection is a resource which event providers create - during the activation process to establish a connection between - the provider and the subscriber channel. - - Attributes: - name (str): - Required. The name of the connection. - uid (str): - Output only. Server assigned ID of the - resource. The server guarantees uniqueness and - immutability until deleted. - channel (str): - Required. The name of the connected subscriber Channel. This - is a weak reference to avoid cross project and cross - accounts references. This must be in - ``projects/{project}/location/{location}/channels/{channel_id}`` - format. - 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. - activation_token (str): - Input only. Activation token for the channel. - The token will be used during the creation of - ChannelConnection to bind the channel with the - provider project. This field will not be stored - in the provider resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uid: str = proto.Field( - proto.STRING, - number=2, - ) - channel: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - activation_token: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py deleted file mode 100644 index d8424067300d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/discovery.py +++ /dev/null @@ -1,149 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.eventarc.v1', - manifest={ - 'Provider', - 'EventType', - 'FilteringAttribute', - }, -) - - -class Provider(proto.Message): - r"""A representation of the Provider resource. - - Attributes: - name (str): - Output only. In - ``projects/{project}/locations/{location}/providers/{provider_id}`` - format. - display_name (str): - Output only. Human friendly name for the - Provider. For example "Cloud Storage". - event_types (MutableSequence[google.cloud.eventarc_v1.types.EventType]): - Output only. Event types for this provider. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - event_types: MutableSequence['EventType'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='EventType', - ) - - -class EventType(proto.Message): - r"""A representation of the event type resource. - - Attributes: - type_ (str): - Output only. The full name of the event type - (for example, - "google.cloud.storage.object.v1.finalized"). In - the form of - {provider-specific-prefix}.{resource}.{version}.{verb}. - Types MUST be versioned and event schemas are - guaranteed to remain backward compatible within - one version. Note that event type versions and - API versions do not need to match. - description (str): - Output only. Human friendly description of - what the event type is about. For example - "Bucket created in Cloud Storage". - filtering_attributes (MutableSequence[google.cloud.eventarc_v1.types.FilteringAttribute]): - Output only. Filtering attributes for the - event type. - event_schema_uri (str): - Output only. URI for the event schema. - For example - "https://github.com/googleapis/google-cloudevents/blob/master/proto/google/events/cloud/storage/v1/events.proto". - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filtering_attributes: MutableSequence['FilteringAttribute'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='FilteringAttribute', - ) - event_schema_uri: str = proto.Field( - proto.STRING, - number=4, - ) - - -class FilteringAttribute(proto.Message): - r"""A representation of the FilteringAttribute resource. - Filtering attributes are per event type. - - Attributes: - attribute (str): - Output only. Attribute used for filtering the - event type. - description (str): - Output only. Description of the purpose of - the attribute. - required (bool): - Output only. If true, the triggers for this - provider should always specify a filter on these - attributes. Trigger creation will fail - otherwise. - path_pattern_supported (bool): - Output only. If true, the attribute accepts - matching expressions in the Eventarc PathPattern - format. - """ - - attribute: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - required: bool = proto.Field( - proto.BOOL, - number=3, - ) - path_pattern_supported: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py deleted file mode 100644 index 86d09339e35a..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/enrollment.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'Enrollment', - }, -) - - -class Enrollment(proto.Message): - r"""An enrollment represents a subscription for messages on a - particular message bus. It defines a matching criteria for - messages on the bus and the subscriber endpoint where matched - messages should be delivered. - - Attributes: - name (str): - Identifier. Resource name of the form - projects/{project}/locations/{location}/enrollments/{enrollment} - uid (str): - Output only. Server assigned unique - identifier for the channel. The value is a UUID4 - string and guaranteed to remain unchanged until - the resource is deleted. - etag (str): - Output only. This checksum is computed by the - server based on the value of other fields, and - might be sent only on update and delete requests - to ensure that the client has an up-to-date - value before proceeding. - 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. - labels (MutableMapping[str, str]): - Optional. Resource labels. - annotations (MutableMapping[str, str]): - Optional. Resource annotations. - display_name (str): - Optional. Resource display name. - cel_match (str): - Required. A CEL expression identifying which - messages this enrollment applies to. - message_bus (str): - Required. Resource name of the message bus - identifying the source of the messages. It - matches the form - projects/{project}/locations/{location}/messageBuses/{messageBus}. - destination (str): - Required. Destination is the Pipeline that the Enrollment is - delivering to. It must point to the full resource name of a - Pipeline. Format: - "projects/{PROJECT_ID}/locations/{region}/pipelines/{PIPELINE_ID)". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uid: str = proto.Field( - proto.STRING, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - 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, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - cel_match: str = proto.Field( - proto.STRING, - number=9, - ) - message_bus: str = proto.Field( - proto.STRING, - number=10, - ) - destination: str = proto.Field( - proto.STRING, - number=11, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py deleted file mode 100644 index 7b3ef6ea4225..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/eventarc.py +++ /dev/null @@ -1,1745 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.eventarc_v1.types import channel as gce_channel -from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment as gce_enrollment -from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus as gce_message_bus -from google.cloud.eventarc_v1.types import pipeline as gce_pipeline -from google.cloud.eventarc_v1.types import trigger as gce_trigger -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'GetTriggerRequest', - 'ListTriggersRequest', - 'ListTriggersResponse', - 'CreateTriggerRequest', - 'UpdateTriggerRequest', - 'DeleteTriggerRequest', - 'GetChannelRequest', - 'ListChannelsRequest', - 'ListChannelsResponse', - 'CreateChannelRequest', - 'UpdateChannelRequest', - 'DeleteChannelRequest', - 'GetProviderRequest', - 'ListProvidersRequest', - 'ListProvidersResponse', - 'GetChannelConnectionRequest', - 'ListChannelConnectionsRequest', - 'ListChannelConnectionsResponse', - 'CreateChannelConnectionRequest', - 'DeleteChannelConnectionRequest', - 'UpdateGoogleChannelConfigRequest', - 'GetGoogleChannelConfigRequest', - 'GetMessageBusRequest', - 'ListMessageBusesRequest', - 'ListMessageBusesResponse', - 'ListMessageBusEnrollmentsRequest', - 'ListMessageBusEnrollmentsResponse', - 'CreateMessageBusRequest', - 'UpdateMessageBusRequest', - 'DeleteMessageBusRequest', - 'GetEnrollmentRequest', - 'ListEnrollmentsRequest', - 'ListEnrollmentsResponse', - 'CreateEnrollmentRequest', - 'UpdateEnrollmentRequest', - 'DeleteEnrollmentRequest', - 'GetPipelineRequest', - 'ListPipelinesRequest', - 'ListPipelinesResponse', - 'CreatePipelineRequest', - 'UpdatePipelineRequest', - 'DeletePipelineRequest', - 'GetGoogleApiSourceRequest', - 'ListGoogleApiSourcesRequest', - 'ListGoogleApiSourcesResponse', - 'CreateGoogleApiSourceRequest', - 'UpdateGoogleApiSourceRequest', - 'DeleteGoogleApiSourceRequest', - 'OperationMetadata', - }, -) - - -class GetTriggerRequest(proto.Message): - r"""The request message for the GetTrigger method. - - Attributes: - name (str): - Required. The name of the trigger to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListTriggersRequest(proto.Message): - r"""The request message for the ListTriggers method. - - Attributes: - parent (str): - Required. The parent collection to list - triggers on. - page_size (int): - The maximum number of triggers to return on - each page. - Note: The service may send fewer. - page_token (str): - The page token; provide the value from the - ``next_page_token`` field in a previous ``ListTriggers`` - call to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListTriggers`` must match the call that provided the page - token. - order_by (str): - The sorting order of the resources returned. Value should be - a comma-separated list of fields. The default sorting order - is ascending. To specify descending order for a field, - append a ``desc`` suffix; for example: - ``name desc, trigger_id``. - filter (str): - Filter field. Used to filter the Triggers to - be listed. Possible filters are described in - https://google.aip.dev/160. For example, using - "?filter=destination:gke" would list only - Triggers with a gke destination. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListTriggersResponse(proto.Message): - r"""The response message for the ``ListTriggers`` method. - - Attributes: - triggers (MutableSequence[google.cloud.eventarc_v1.types.Trigger]): - The requested triggers, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListTriggers`` to request - the next page. If this is empty, then there are no more - pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - triggers: MutableSequence[gce_trigger.Trigger] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_trigger.Trigger, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateTriggerRequest(proto.Message): - r"""The request message for the CreateTrigger method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this trigger. - trigger (google.cloud.eventarc_v1.types.Trigger): - Required. The trigger to create. - trigger_id (str): - Required. The user-provided ID to be assigned - to the trigger. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - trigger: gce_trigger.Trigger = proto.Field( - proto.MESSAGE, - number=2, - message=gce_trigger.Trigger, - ) - trigger_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateTriggerRequest(proto.Message): - r"""The request message for the UpdateTrigger method. - - Attributes: - trigger (google.cloud.eventarc_v1.types.Trigger): - The trigger to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to be updated; only fields explicitly provided - are updated. If no field mask is provided, all provided - fields in the request are updated. To update all fields, - provide a field mask of "*". - allow_missing (bool): - If set to true, and the trigger is not found, a new trigger - will be created. In this situation, ``update_mask`` is - ignored. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - trigger: gce_trigger.Trigger = proto.Field( - proto.MESSAGE, - number=1, - message=gce_trigger.Trigger, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteTriggerRequest(proto.Message): - r"""The request message for the DeleteTrigger method. - - Attributes: - name (str): - Required. The name of the trigger to be - deleted. - etag (str): - If provided, the trigger will only be deleted - if the etag matches the current etag on the - resource. - allow_missing (bool): - If set to true, and the trigger is not found, - the request will succeed but no action will be - taken on the server. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - etag: str = proto.Field( - proto.STRING, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetChannelRequest(proto.Message): - r"""The request message for the GetChannel method. - - Attributes: - name (str): - Required. The name of the channel to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListChannelsRequest(proto.Message): - r"""The request message for the ListChannels method. - - Attributes: - parent (str): - Required. The parent collection to list - channels on. - page_size (int): - The maximum number of channels to return on - each page. - Note: The service may send fewer. - page_token (str): - The page token; provide the value from the - ``next_page_token`` field in a previous ``ListChannels`` - call to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListChannels`` must match the call that provided the page - token. - order_by (str): - The sorting order of the resources returned. Value should be - a comma-separated list of fields. The default sorting order - is ascending. To specify descending order for a field, - append a ``desc`` suffix; for example: - ``name desc, channel_id``. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListChannelsResponse(proto.Message): - r"""The response message for the ``ListChannels`` method. - - Attributes: - channels (MutableSequence[google.cloud.eventarc_v1.types.Channel]): - The requested channels, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListChannels`` to request - the next page. If this is empty, then there are no more - pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - channels: MutableSequence[gce_channel.Channel] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_channel.Channel, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateChannelRequest(proto.Message): - r"""The request message for the CreateChannel method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this channel. - channel (google.cloud.eventarc_v1.types.Channel): - Required. The channel to create. - channel_id (str): - Required. The user-provided ID to be assigned - to the channel. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - channel: gce_channel.Channel = proto.Field( - proto.MESSAGE, - number=2, - message=gce_channel.Channel, - ) - channel_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateChannelRequest(proto.Message): - r"""The request message for the UpdateChannel method. - - Attributes: - channel (google.cloud.eventarc_v1.types.Channel): - The channel to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to be updated; only fields explicitly provided - are updated. If no field mask is provided, all provided - fields in the request are updated. To update all fields, - provide a field mask of "*". - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - channel: gce_channel.Channel = proto.Field( - proto.MESSAGE, - number=1, - message=gce_channel.Channel, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteChannelRequest(proto.Message): - r"""The request message for the DeleteChannel method. - - Attributes: - name (str): - Required. The name of the channel to be - deleted. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class GetProviderRequest(proto.Message): - r"""The request message for the GetProvider method. - - Attributes: - name (str): - Required. The name of the provider to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProvidersRequest(proto.Message): - r"""The request message for the ListProviders method. - - Attributes: - parent (str): - Required. The parent of the provider to get. - page_size (int): - The maximum number of providers to return on - each page. - page_token (str): - The page token; provide the value from the - ``next_page_token`` field in a previous ``ListProviders`` - call to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListProviders`` must match the call that provided the page - token. - order_by (str): - The sorting order of the resources returned. Value should be - a comma-separated list of fields. The default sorting oder - is ascending. To specify descending order for a field, - append a ``desc`` suffix; for example: ``name desc, _id``. - filter (str): - The filter field that the list request will - filter on. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListProvidersResponse(proto.Message): - r"""The response message for the ``ListProviders`` method. - - Attributes: - providers (MutableSequence[google.cloud.eventarc_v1.types.Provider]): - The requested providers, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListProviders`` to - request the next page. If this is empty, then there are no - more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - providers: MutableSequence[discovery.Provider] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=discovery.Provider, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetChannelConnectionRequest(proto.Message): - r"""The request message for the GetChannelConnection method. - - Attributes: - name (str): - Required. The name of the channel connection - to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListChannelConnectionsRequest(proto.Message): - r"""The request message for the ListChannelConnections method. - - Attributes: - parent (str): - Required. The parent collection from which to - list channel connections. - page_size (int): - The maximum number of channel connections to - return on each page. - Note: The service may send fewer responses. - page_token (str): - The page token; provide the value from the - ``next_page_token`` field in a previous - ``ListChannelConnections`` call to retrieve the subsequent - page. - - When paginating, all other parameters provided to - ``ListChannelConnetions`` match the call that provided the - page token. - """ - - 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 ListChannelConnectionsResponse(proto.Message): - r"""The response message for the ``ListChannelConnections`` method. - - Attributes: - channel_connections (MutableSequence[google.cloud.eventarc_v1.types.ChannelConnection]): - The requested channel connections, up to the number - specified in ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListChannelConnections`` - to request the next page. If this is empty, then there are - no more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - channel_connections: MutableSequence[gce_channel_connection.ChannelConnection] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_channel_connection.ChannelConnection, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateChannelConnectionRequest(proto.Message): - r"""The request message for the CreateChannelConnection method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this channel connection. - channel_connection (google.cloud.eventarc_v1.types.ChannelConnection): - Required. Channel connection to create. - channel_connection_id (str): - Required. The user-provided ID to be assigned - to the channel connection. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - channel_connection: gce_channel_connection.ChannelConnection = proto.Field( - proto.MESSAGE, - number=2, - message=gce_channel_connection.ChannelConnection, - ) - channel_connection_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteChannelConnectionRequest(proto.Message): - r"""The request message for the DeleteChannelConnection method. - - Attributes: - name (str): - Required. The name of the channel connection - to delete. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateGoogleChannelConfigRequest(proto.Message): - r"""The request message for the UpdateGoogleChannelConfig method. - - Attributes: - google_channel_config (google.cloud.eventarc_v1.types.GoogleChannelConfig): - Required. The config to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to be updated; only fields explicitly provided - are updated. If no field mask is provided, all provided - fields in the request are updated. To update all fields, - provide a field mask of "*". - """ - - google_channel_config: gce_google_channel_config.GoogleChannelConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gce_google_channel_config.GoogleChannelConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetGoogleChannelConfigRequest(proto.Message): - r"""The request message for the GetGoogleChannelConfig method. - - Attributes: - name (str): - Required. The name of the config to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetMessageBusRequest(proto.Message): - r"""The request message for the GetMessageBus method. - - Attributes: - name (str): - Required. The name of the message bus to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListMessageBusesRequest(proto.Message): - r"""The request message for the ListMessageBuses method. - - Attributes: - parent (str): - Required. The parent collection to list - triggers on. - page_size (int): - Optional. The maximum number of results to - return on each page. - Note: The service may send fewer. - page_token (str): - Optional. The page token; provide the value from the - ``next_page_token`` field in a previous call to retrieve the - subsequent page. - - When paginating, all other parameters provided must match - the previous call that provided the page token. - order_by (str): - Optional. The sorting order of the resources returned. Value - should be a comma-separated list of fields. The default - sorting order is ascending. To specify descending order for - a field, append a ``desc`` suffix; for example: - ``name desc, update_time``. - filter (str): - Optional. The filter field that the list - request will filter on. Possible filtersare - described in https://google.aip.dev/160. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListMessageBusesResponse(proto.Message): - r"""The response message for the ``ListMessageBuses`` method. - - Attributes: - message_buses (MutableSequence[google.cloud.eventarc_v1.types.MessageBus]): - The requested message buses, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListMessageBuses`` to - request the next page. If this is empty, then there are no - more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - message_buses: MutableSequence[gce_message_bus.MessageBus] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_message_bus.MessageBus, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListMessageBusEnrollmentsRequest(proto.Message): - r"""The request message for the ``ListMessageBusEnrollments`` method. - - Attributes: - parent (str): - Required. The parent message bus to list - enrollments on. - page_size (int): - Optional. The maximum number of results to - return on each page. - Note: The service may send fewer. - page_token (str): - Optional. The page token; provide the value from the - ``next_page_token`` field in a previous call to retrieve the - subsequent page. - - When paginating, all other parameters provided must match - the previous call that provided the page token. - """ - - 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 ListMessageBusEnrollmentsResponse(proto.Message): - r"""The response message for the ``ListMessageBusEnrollments`` method.\` - - Attributes: - enrollments (MutableSequence[str]): - The requested enrollments, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to - ``ListMessageBusEnrollments`` to request the next page. If - this is empty, then there are no more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - enrollments: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateMessageBusRequest(proto.Message): - r"""The request message for the CreateMessageBus method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this message bus. - message_bus (google.cloud.eventarc_v1.types.MessageBus): - Required. The message bus to create. - message_bus_id (str): - Required. The user-provided ID to be assigned to the - MessageBus. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - message_bus: gce_message_bus.MessageBus = proto.Field( - proto.MESSAGE, - number=2, - message=gce_message_bus.MessageBus, - ) - message_bus_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateMessageBusRequest(proto.Message): - r"""The request message for the UpdateMessageBus method. - - Attributes: - message_bus (google.cloud.eventarc_v1.types.MessageBus): - Required. The MessageBus to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update all - fields, provide a field mask of "*". - allow_missing (bool): - Optional. If set to true, and the MessageBus is not found, a - new MessageBus will be created. In this situation, - ``update_mask`` is ignored. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - message_bus: gce_message_bus.MessageBus = proto.Field( - proto.MESSAGE, - number=1, - message=gce_message_bus.MessageBus, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteMessageBusRequest(proto.Message): - r"""The request message for the DeleteMessageBus method. - - Attributes: - name (str): - Required. The name of the MessageBus to be - deleted. - etag (str): - Optional. If provided, the MessageBus will - only be deleted if the etag matches the current - etag on the resource. - allow_missing (bool): - Optional. If set to true, and the MessageBus - is not found, the request will succeed but no - action will be taken on the server. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - etag: str = proto.Field( - proto.STRING, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetEnrollmentRequest(proto.Message): - r"""The request message for the GetEnrollment method. - - Attributes: - name (str): - Required. The name of the Enrollment to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEnrollmentsRequest(proto.Message): - r"""The request message for the ListEnrollments method. - - Attributes: - parent (str): - Required. The parent collection to list - triggers on. - page_size (int): - Optional. The maximum number of results to - return on each page. - Note: The service may send fewer. - page_token (str): - Optional. The page token; provide the value from the - ``next_page_token`` field in a previous call to retrieve the - subsequent page. - - When paginating, all other parameters provided must match - the previous call that provided the page token. - order_by (str): - Optional. The sorting order of the resources returned. Value - should be a comma-separated list of fields. The default - sorting order is ascending. To specify descending order for - a field, append a ``desc`` suffix; for example: - ``name desc, update_time``. - filter (str): - Optional. The filter field that the list - request will filter on. Possible filtersare - described in https://google.aip.dev/160. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListEnrollmentsResponse(proto.Message): - r"""The response message for the ``ListEnrollments`` method. - - Attributes: - enrollments (MutableSequence[google.cloud.eventarc_v1.types.Enrollment]): - The requested Enrollments, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListEnrollments`` to - request the next page. If this is empty, then there are no - more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - enrollments: MutableSequence[gce_enrollment.Enrollment] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_enrollment.Enrollment, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateEnrollmentRequest(proto.Message): - r"""The request message for the CreateEnrollment method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this enrollment. - enrollment (google.cloud.eventarc_v1.types.Enrollment): - Required. The enrollment to create. - enrollment_id (str): - Required. The user-provided ID to be assigned to the - Enrollment. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - enrollment: gce_enrollment.Enrollment = proto.Field( - proto.MESSAGE, - number=2, - message=gce_enrollment.Enrollment, - ) - enrollment_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateEnrollmentRequest(proto.Message): - r"""The request message for the UpdateEnrollment method. - - Attributes: - enrollment (google.cloud.eventarc_v1.types.Enrollment): - Required. The Enrollment to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update all - fields, provide a field mask of "*". - allow_missing (bool): - Optional. If set to true, and the Enrollment is not found, a - new Enrollment will be created. In this situation, - ``update_mask`` is ignored. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - enrollment: gce_enrollment.Enrollment = proto.Field( - proto.MESSAGE, - number=1, - message=gce_enrollment.Enrollment, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteEnrollmentRequest(proto.Message): - r"""The request message for the DeleteEnrollment method. - - Attributes: - name (str): - Required. The name of the Enrollment to be - deleted. - etag (str): - Optional. If provided, the Enrollment will - only be deleted if the etag matches the current - etag on the resource. - allow_missing (bool): - Optional. If set to true, and the Enrollment - is not found, the request will succeed but no - action will be taken on the server. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - etag: str = proto.Field( - proto.STRING, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetPipelineRequest(proto.Message): - r"""The request message for the GetPipeline method. - - Attributes: - name (str): - Required. The name of the pipeline to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListPipelinesRequest(proto.Message): - r"""The request message for the ListPipelines method. - - Attributes: - parent (str): - Required. The parent collection to list - pipelines on. - page_size (int): - Optional. The maximum number of results to - return on each page. - Note: The service may send fewer. - page_token (str): - Optional. The page token; provide the value from the - ``next_page_token`` field in a previous call to retrieve the - subsequent page. - - When paginating, all other parameters provided must match - the previous call that provided the page token. - order_by (str): - Optional. The sorting order of the resources returned. Value - should be a comma-separated list of fields. The default - sorting order is ascending. To specify descending order for - a field, append a ``desc`` suffix; for example: - ``name desc, update_time``. - filter (str): - Optional. The filter field that the list - request will filter on. Possible filters are - described in https://google.aip.dev/160. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListPipelinesResponse(proto.Message): - r"""The response message for the ListPipelines method. - - Attributes: - pipelines (MutableSequence[google.cloud.eventarc_v1.types.Pipeline]): - The requested pipelines, up to the number specified in - ``page_size``. - next_page_token (str): - A page token that can be sent to ``ListPipelines`` to - request the next page. If this is empty, then there are no - more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - pipelines: MutableSequence[gce_pipeline.Pipeline] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_pipeline.Pipeline, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreatePipelineRequest(proto.Message): - r"""The request message for the CreatePipeline method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this pipeline. - pipeline (google.cloud.eventarc_v1.types.Pipeline): - Required. The pipeline to create. - pipeline_id (str): - Required. The user-provided ID to be assigned - to the Pipeline. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - pipeline: gce_pipeline.Pipeline = proto.Field( - proto.MESSAGE, - number=2, - message=gce_pipeline.Pipeline, - ) - pipeline_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdatePipelineRequest(proto.Message): - r"""The request message for the UpdatePipeline method. - - Attributes: - pipeline (google.cloud.eventarc_v1.types.Pipeline): - Required. The Pipeline to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update all - fields, provide a field mask of "*". - allow_missing (bool): - Optional. If set to true, and the Pipeline is not found, a - new Pipeline will be created. In this situation, - ``update_mask`` is ignored. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - pipeline: gce_pipeline.Pipeline = proto.Field( - proto.MESSAGE, - number=1, - message=gce_pipeline.Pipeline, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeletePipelineRequest(proto.Message): - r"""The request message for the DeletePipeline method. - - Attributes: - name (str): - Required. The name of the Pipeline to be - deleted. - etag (str): - Optional. If provided, the Pipeline will only - be deleted if the etag matches the current etag - on the resource. - allow_missing (bool): - Optional. If set to true, and the Pipeline is - not found, the request will succeed but no - action will be taken on the server. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - etag: str = proto.Field( - proto.STRING, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetGoogleApiSourceRequest(proto.Message): - r"""The request message for the GetGoogleApiSource method. - - Attributes: - name (str): - Required. The name of the google api source - to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListGoogleApiSourcesRequest(proto.Message): - r"""The request message for the ListGoogleApiSources method. - - Attributes: - parent (str): - Required. The parent collection to list - GoogleApiSources on. - page_size (int): - Optional. The maximum number of results to - return on each page. - Note: The service may send fewer. - page_token (str): - Optional. The page token; provide the value from the - ``next_page_token`` field in a previous call to retrieve the - subsequent page. - - When paginating, all other parameters provided must match - the previous call that provided the page token. - order_by (str): - Optional. The sorting order of the resources returned. Value - should be a comma-separated list of fields. The default - sorting order is ascending. To specify descending order for - a field, append a ``desc`` suffix; for example: - ``name desc, update_time``. - filter (str): - Optional. The filter field that the list - request will filter on. Possible filtersare - described in https://google.aip.dev/160. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=4, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListGoogleApiSourcesResponse(proto.Message): - r"""The response message for the ``ListGoogleApiSources`` method. - - Attributes: - google_api_sources (MutableSequence[google.cloud.eventarc_v1.types.GoogleApiSource]): - The requested GoogleApiSources, up to the number specified - in ``page_size``. - next_page_token (str): - A page token that can be sent to - ``ListMessageBusEnrollments`` to request the next page. If - this is empty, then there are no more pages. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - google_api_sources: MutableSequence[gce_google_api_source.GoogleApiSource] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gce_google_api_source.GoogleApiSource, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateGoogleApiSourceRequest(proto.Message): - r"""The request message for the CreateGoogleApiSource method. - - Attributes: - parent (str): - Required. The parent collection in which to - add this google api source. - google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): - Required. The google api source to create. - google_api_source_id (str): - Required. The user-provided ID to be assigned to the - GoogleApiSource. It should match the format - (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - google_api_source: gce_google_api_source.GoogleApiSource = proto.Field( - proto.MESSAGE, - number=2, - message=gce_google_api_source.GoogleApiSource, - ) - google_api_source_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateGoogleApiSourceRequest(proto.Message): - r"""The request message for the UpdateGoogleApiSource method. - - Attributes: - google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): - Required. The GoogleApiSource to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The fields to be updated; only fields explicitly - provided are updated. If no field mask is provided, all - provided fields in the request are updated. To update all - fields, provide a field mask of "*". - allow_missing (bool): - Optional. If set to true, and the GoogleApiSource is not - found, a new GoogleApiSource will be created. In this - situation, ``update_mask`` is ignored. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - google_api_source: gce_google_api_source.GoogleApiSource = proto.Field( - proto.MESSAGE, - number=1, - message=gce_google_api_source.GoogleApiSource, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteGoogleApiSourceRequest(proto.Message): - r"""The request message for the DeleteGoogleApiSource method. - - Attributes: - name (str): - Required. The name of the GoogleApiSource to - be deleted. - etag (str): - Optional. If provided, the MessageBus will - only be deleted if the etag matches the current - etag on the resource. - allow_missing (bool): - Optional. If set to true, and the MessageBus - is not found, the request will succeed but no - action will be taken on the server. - validate_only (bool): - Optional. If set, validate the request and - preview the review, but do not post it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - etag: str = proto.Field( - proto.STRING, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has requested - cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py deleted file mode 100644 index daf49f4929b8..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_api_source.py +++ /dev/null @@ -1,130 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.eventarc_v1.types import logging_config as gce_logging_config -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'GoogleApiSource', - }, -) - - -class GoogleApiSource(proto.Message): - r"""A GoogleApiSource represents a subscription of 1P events from - a MessageBus. - - Attributes: - name (str): - Identifier. Resource name of the form - projects/{project}/locations/{location}/googleApiSources/{google_api_source} - uid (str): - Output only. Server assigned unique - identifier for the channel. The value is a UUID4 - string and guaranteed to remain unchanged until - the resource is deleted. - etag (str): - Output only. This checksum is computed by the - server based on the value of other fields, and - might be sent only on update and delete requests - to ensure that the client has an up-to-date - value before proceeding. - 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. - labels (MutableMapping[str, str]): - Optional. Resource labels. - annotations (MutableMapping[str, str]): - Optional. Resource annotations. - display_name (str): - Optional. Resource display name. - destination (str): - Required. Destination is the message bus that the - GoogleApiSource is delivering to. It must be point to the - full resource name of a MessageBus. Format: - "projects/{PROJECT_ID}/locations/{region}/messagesBuses/{MESSAGE_BUS_ID) - crypto_key_name (str): - Optional. Resource name of a KMS crypto key (managed by the - user) used to encrypt/decrypt their event data. - - It must match the pattern - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - logging_config (google.cloud.eventarc_v1.types.LoggingConfig): - Optional. Config to control Platform logging - for the GoogleApiSource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uid: str = proto.Field( - proto.STRING, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - 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, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - destination: str = proto.Field( - proto.STRING, - number=9, - ) - crypto_key_name: str = proto.Field( - proto.STRING, - number=10, - ) - logging_config: gce_logging_config.LoggingConfig = proto.Field( - proto.MESSAGE, - number=11, - message=gce_logging_config.LoggingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py deleted file mode 100644 index c99e4bc09554..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/google_channel_config.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'GoogleChannelConfig', - }, -) - - -class GoogleChannelConfig(proto.Message): - r"""A GoogleChannelConfig is a resource that stores the custom - settings respected by Eventarc first-party triggers in the - matching region. Once configured, first-party event data will be - protected using the specified custom managed encryption key - instead of Google-managed encryption keys. - - Attributes: - name (str): - Required. The resource name of the config. Must be in the - format of, - ``projects/{project}/locations/{location}/googleChannelConfig``. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last-modified time. - crypto_key_name (str): - Optional. Resource name of a KMS crypto key (managed by the - user) used to encrypt/decrypt their event data. - - It must match the pattern - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - crypto_key_name: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py deleted file mode 100644 index 31f742eb9a89..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/logging_config.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.eventarc.v1', - manifest={ - 'LoggingConfig', - }, -) - - -class LoggingConfig(proto.Message): - r"""The configuration for Platform Telemetry logging for Eventarc - Advanced resources. - - Attributes: - log_severity (google.cloud.eventarc_v1.types.LoggingConfig.LogSeverity): - Optional. The minimum severity of logs that - will be sent to Stackdriver/Platform Telemetry. - Logs at severitiy ≥ this value will be sent, - unless it is NONE. - """ - class LogSeverity(proto.Enum): - r"""The different severities for logging supported by Eventarc - Advanced resources. - This enum is an exhaustive list of log severities and is FROZEN. - Do not expect new values to be added. - - Values: - LOG_SEVERITY_UNSPECIFIED (0): - Log severity is not specified. This value is treated the - same as NONE, but is used to distinguish between no update - and update to NONE in update_masks. - NONE (1): - Default value at resource creation, presence - of this value must be treated as no - logging/disable logging. - DEBUG (2): - Debug or trace level logging. - INFO (3): - Routine information, such as ongoing status - or performance. - NOTICE (4): - Normal but significant events, such as start - up, shut down, or a configuration change. - WARNING (5): - Warning events might cause problems. - ERROR (6): - Error events are likely to cause problems. - CRITICAL (7): - Critical events cause more severe problems or - outages. - ALERT (8): - A person must take action immediately. - EMERGENCY (9): - One or more systems are unusable. - """ - LOG_SEVERITY_UNSPECIFIED = 0 - NONE = 1 - DEBUG = 2 - INFO = 3 - NOTICE = 4 - WARNING = 5 - ERROR = 6 - CRITICAL = 7 - ALERT = 8 - EMERGENCY = 9 - - log_severity: LogSeverity = proto.Field( - proto.ENUM, - number=1, - enum=LogSeverity, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py deleted file mode 100644 index 826c24bd5950..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/message_bus.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.eventarc_v1.types import logging_config as gce_logging_config -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'MessageBus', - }, -) - - -class MessageBus(proto.Message): - r"""MessageBus for the messages flowing through the system. The - admin has visibility and control over the messages being - published and consumed and can restrict publishers and - subscribers to only a subset of data available in the system by - defining authorization policies. - - Attributes: - name (str): - Identifier. Resource name of the form - projects/{project}/locations/{location}/messageBuses/{message_bus} - uid (str): - Output only. Server assigned unique - identifier for the channel. The value is a UUID4 - string and guaranteed to remain unchanged until - the resource is deleted. - etag (str): - Output only. This checksum is computed by the - server based on the value of other fields, and - might be sent only on update and delete requests - to ensure that the client has an up-to-date - value before proceeding. - 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. - labels (MutableMapping[str, str]): - Optional. Resource labels. - annotations (MutableMapping[str, str]): - Optional. Resource annotations. - display_name (str): - Optional. Resource display name. - crypto_key_name (str): - Optional. Resource name of a KMS crypto key (managed by the - user) used to encrypt/decrypt their event data. - - It must match the pattern - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - logging_config (google.cloud.eventarc_v1.types.LoggingConfig): - Optional. Config to control Platform logging - for the Message Bus. This log configuration is - applied to the Message Bus itself, and all the - Enrollments attached to it. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uid: str = proto.Field( - proto.STRING, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - 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, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - crypto_key_name: str = proto.Field( - proto.STRING, - number=10, - ) - logging_config: gce_logging_config.LoggingConfig = proto.Field( - proto.MESSAGE, - number=11, - message=gce_logging_config.LoggingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py deleted file mode 100644 index 46d0cc094778..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/network_config.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.eventarc.v1', - manifest={ - 'NetworkConfig', - }, -) - - -class NetworkConfig(proto.Message): - r"""Network Configuration that can be inherited by other protos. - - Attributes: - network_attachment (str): - Required. Name of the NetworkAttachment that allows access - to the customer's VPC. Format: - ``projects/{PROJECT_ID}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}`` - """ - - network_attachment: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py deleted file mode 100644 index d0c483f718ad..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/pipeline.py +++ /dev/null @@ -1,838 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.eventarc_v1.types import logging_config as gce_logging_config -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'Pipeline', - }, -) - - -class Pipeline(proto.Message): - r"""A representation of the Pipeline resource. - - Attributes: - name (str): - Identifier. The resource name of the Pipeline. Must be - unique within the location of the project and must be in - ``projects/{project}/locations/{location}/pipelines/{pipeline}`` - format. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation time. - A timestamp in RFC3339 UTC "Zulu" format, with - nanosecond resolution and up to nine fractional - digits. Examples: "2014-10-02T15:01:23Z" and - "2014-10-02T15:01:23.045123456Z". - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last-modified time. - A timestamp in RFC3339 UTC "Zulu" format, with - nanosecond resolution and up to nine fractional - digits. Examples: "2014-10-02T15:01:23Z" and - "2014-10-02T15:01:23.045123456Z". - labels (MutableMapping[str, str]): - Optional. User labels attached to the - Pipeline that can be used to group resources. An - object containing a list of "key": value pairs. - Example: { "name": "wrench", "mass": "1.3kg", - "count": "3" }. - uid (str): - Output only. Server-assigned unique - identifier for the Pipeline. The value is a - UUID4 string and guaranteed to remain unchanged - until the resource is deleted. - annotations (MutableMapping[str, str]): - Optional. User-defined annotations. See - https://google.aip.dev/128#annotations. - display_name (str): - Optional. Display name of resource. - destinations (MutableSequence[google.cloud.eventarc_v1.types.Pipeline.Destination]): - Required. List of destinations to which - messages will be forwarded. Currently, exactly - one destination is supported per Pipeline. - mediations (MutableSequence[google.cloud.eventarc_v1.types.Pipeline.Mediation]): - Optional. List of mediation operations to be - performed on the message. Currently, only one - Transformation operation is allowed in each - Pipeline. - crypto_key_name (str): - Optional. Resource name of a KMS crypto key - (managed by the user) used to encrypt/decrypt - the event data. If not set, an internal - Google-owned key will be used to encrypt - messages. It must match the pattern - "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}". - input_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): - Optional. The payload format expected for the messages - received by the Pipeline. If input_payload_format is set - then any messages not matching this format will be treated - as persistent errors. If input_payload_format is not set, - then the message data will be treated as an opaque binary - and no output format can be set on the Pipeline through the - Pipeline.Destination.output_payload_format field. Any - Mediations on the Pipeline that involve access to the data - field will fail as persistent errors. - logging_config (google.cloud.eventarc_v1.types.LoggingConfig): - Optional. Config to control Platform Logging - for Pipelines. - retry_policy (google.cloud.eventarc_v1.types.Pipeline.RetryPolicy): - Optional. The retry policy to use in the - pipeline. - etag (str): - Output only. This checksum is computed by the - server based on the value of other fields, and - might be sent only on create requests to ensure - that the client has an up-to-date value before - proceeding. - """ - - class MessagePayloadFormat(proto.Message): - r"""Represents the format of message data. - - 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: - protobuf (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.ProtobufFormat): - Optional. Protobuf format. - - This field is a member of `oneof`_ ``kind``. - avro (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.AvroFormat): - Optional. Avro format. - - This field is a member of `oneof`_ ``kind``. - json (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.JsonFormat): - Optional. JSON format. - - This field is a member of `oneof`_ ``kind``. - """ - - class JsonFormat(proto.Message): - r"""The format of a JSON message payload. - """ - - class ProtobufFormat(proto.Message): - r"""The format of a Protobuf message payload. - - Attributes: - schema_definition (str): - Optional. The entire schema definition is - stored in this field. - """ - - schema_definition: str = proto.Field( - proto.STRING, - number=1, - ) - - class AvroFormat(proto.Message): - r"""The format of an AVRO message payload. - - Attributes: - schema_definition (str): - Optional. The entire schema definition is - stored in this field. - """ - - schema_definition: str = proto.Field( - proto.STRING, - number=1, - ) - - protobuf: 'Pipeline.MessagePayloadFormat.ProtobufFormat' = proto.Field( - proto.MESSAGE, - number=1, - oneof='kind', - message='Pipeline.MessagePayloadFormat.ProtobufFormat', - ) - avro: 'Pipeline.MessagePayloadFormat.AvroFormat' = proto.Field( - proto.MESSAGE, - number=2, - oneof='kind', - message='Pipeline.MessagePayloadFormat.AvroFormat', - ) - json: 'Pipeline.MessagePayloadFormat.JsonFormat' = proto.Field( - proto.MESSAGE, - number=3, - oneof='kind', - message='Pipeline.MessagePayloadFormat.JsonFormat', - ) - - class Destination(proto.Message): - r"""Represents a target of an invocation over HTTP. - - 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: - network_config (google.cloud.eventarc_v1.types.Pipeline.Destination.NetworkConfig): - Optional. Network config is used to configure - how Pipeline resolves and connects to a - destination. - http_endpoint (google.cloud.eventarc_v1.types.Pipeline.Destination.HttpEndpoint): - Optional. An HTTP endpoint destination described by an URI. - If a DNS FQDN is provided as the endpoint, Pipeline will - create a peering zone to the consumer VPC and forward DNS - requests to the VPC specified by network config to resolve - the service endpoint. See: - https://cloud.google.com/dns/docs/zones/zones-overview#peering_zones - - This field is a member of `oneof`_ ``destination_descriptor``. - workflow (str): - Optional. The resource name of the Workflow whose Executions - are triggered by the events. The Workflow resource should be - deployed in the same project as the Pipeline. Format: - ``projects/{project}/locations/{location}/workflows/{workflow}`` - - This field is a member of `oneof`_ ``destination_descriptor``. - message_bus (str): - Optional. The resource name of the Message Bus to which - events should be published. The Message Bus resource should - exist in the same project as the Pipeline. Format: - ``projects/{project}/locations/{location}/messageBuses/{message_bus}`` - - This field is a member of `oneof`_ ``destination_descriptor``. - topic (str): - Optional. The resource name of the Pub/Sub topic to which - events should be published. Format: - ``projects/{project}/locations/{location}/topics/{topic}`` - - This field is a member of `oneof`_ ``destination_descriptor``. - authentication_config (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig): - Optional. An authentication config used to - authenticate message requests, such that - destinations can verify the source. For example, - this can be used with private GCP destinations - that require GCP credentials to access like - Cloud Run. This field is optional and should be - set only by users interested in authenticated - push - output_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): - Optional. The message format before it is delivered to the - destination. If not set, the message will be delivered in - the format it was originally delivered to the Pipeline. This - field can only be set if Pipeline.input_payload_format is - also set. - """ - - class NetworkConfig(proto.Message): - r"""Represents a network config to be used for destination - resolution and connectivity. - - Attributes: - network_attachment (str): - Required. Name of the NetworkAttachment that allows access - to the consumer VPC. Format: - ``projects/{PROJECT_ID}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}`` - """ - - network_attachment: str = proto.Field( - proto.STRING, - number=1, - ) - - class HttpEndpoint(proto.Message): - r"""Represents a HTTP endpoint destination. - - Attributes: - uri (str): - Required. The URI of the HTTP enpdoint. - - The value must be a RFC2396 URI string. Examples: - ``https://svc.us-central1.p.local:8080/route``. Only the - HTTPS protocol is supported. - message_binding_template (str): - Optional. The CEL expression used to modify how the - destination-bound HTTP request is constructed. - - If a binding expression is not specified here, the message - is treated as a CloudEvent and is mapped to the HTTP request - according to the CloudEvent HTTP Protocol Binding Binary - Content Mode. In this representation, all fields except the - ``data`` and ``datacontenttype`` field on the message are - mapped to HTTP request headers with a prefix of ``ce-``. - - To construct the HTTP request payload and the value of the - content-type HTTP header, the payload format is defined as - follows: - - 1) Use the output_payload_format_type on the - Pipeline.Destination if it is set, else: - 2) Use the input_payload_format_type on the Pipeline if it - is set, else: - 3) Treat the payload as opaque binary data. - - The ``data`` field of the message is converted to the - payload format or left as-is for case 3) and then attached - as the payload of the HTTP request. The ``content-type`` - header on the HTTP request is set to the payload format type - or left empty for case 3). However, if a mediation has - updated the ``datacontenttype`` field on the message so that - it is not the same as the payload format type but it is - still a prefix of the payload format type, then the - ``content-type`` header on the HTTP request is set to this - ``datacontenttype`` value. For example, if the - ``datacontenttype`` is "application/json" and the payload - format type is "application/json; charset=utf-8", then the - ``content-type`` header on the HTTP request is set to - "application/json; charset=utf-8". - - If a non-empty binding expression is specified then this - expression is used to modify the default CloudEvent HTTP - Protocol Binding Binary Content representation. The result - of the CEL expression must be a map of key/value pairs which - is used as follows: - - - If a map named ``headers`` exists on the result of the - expression, then its key/value pairs are directly mapped - to the HTTP request headers. The headers values are - constructed from the corresponding value type’s canonical - representation. If the ``headers`` field doesn’t exist - then the resulting HTTP request will be the headers of - the CloudEvent HTTP Binding Binary Content Mode - representation of the final message. Note: If the - specified binding expression, has updated the - ``datacontenttype`` field on the message so that it is - not the same as the payload format type but it is still a - prefix of the payload format type, then the - ``content-type`` header in the ``headers`` map is set to - this ``datacontenttype`` value. - - If a field named ``body`` exists on the result of the - expression then its value is directly mapped to the body - of the request. If the value of the ``body`` field is of - type bytes or string then it is used for the HTTP request - body as-is, with no conversion. If the body field is of - any other type then it is converted to a JSON string. If - the body field does not exist then the resulting payload - of the HTTP request will be data value of the CloudEvent - HTTP Binding Binary Content Mode representation of the - final message as described earlier. - - Any other fields in the resulting expression will be - ignored. - - The CEL expression may access the incoming CloudEvent - message in its definition, as follows: - - - The ``data`` field of the incoming CloudEvent message can - be accessed using the ``message.data`` value. Subfields - of ``message.data`` may also be accessed if an - input_payload_format has been specified on the Pipeline. - - Each attribute of the incoming CloudEvent message can be - accessed using the ``message.`` value, where is - replaced with the name of the attribute. - - Existing headers can be accessed in the CEL expression - using the ``headers`` variable. The ``headers`` variable - defines a map of key/value pairs corresponding to the - HTTP headers of the CloudEvent HTTP Binding Binary - Content Mode representation of the final message as - described earlier. For example, the following CEL - expression can be used to construct an HTTP request by - adding an additional header to the HTTP headers of the - CloudEvent HTTP Binding Binary Content Mode - representation of the final message and by overwriting - the body of the request: - - :: - - { - "headers": headers.merge({"new-header-key": "new-header-value"}), - "body": "new-body" - } - - Additionally, the following CEL extension functions are - provided for use in this CEL expression: - - - toBase64Url: map.toBase64Url() -> string - - - Converts a CelValue to a base64url encoded string - - - toJsonString: map.toJsonString() -> string - - - Converts a CelValue to a JSON string - - - merge: map1.merge(map2) -> map3 - - - Merges the passed CEL map with the existing CEL map - the function is applied to. - - If the same key exists in both maps, if the key's - value is type map both maps are merged else the value - from the passed map is used. - - - denormalize: map.denormalize() -> map - - - Denormalizes a CEL map such that every value of type - map or key in the map is expanded to return a single - level map. - - The resulting keys are "." separated indices of the - map keys. - - For example: { "a": 1, "b": { "c": 2, "d": 3 } "e": - [4, 5] } .denormalize() -> { "a": 1, "b.c": 2, "b.d": - 3, "e.0": 4, "e.1": 5 } - - - setField: map.setField(key, value) -> message - - - Sets the field of the message with the given key to - the given value. - - If the field is not present it will be added. - - If the field is present it will be overwritten. - - The key can be a dot separated path to set a field in - a nested message. - - Key must be of type string. - - Value may be any valid type. - - - removeFields: map.removeFields([key1, key2, ...]) -> - message - - - Removes the fields of the map with the given keys. - - The keys can be a dot separated path to remove a field - in a nested message. - - If a key is not found it will be ignored. - - Keys must be of type string. - - - toMap: [map1, map2, ...].toMap() -> map - - - Converts a CEL list of CEL maps to a single CEL map - - - toDestinationPayloadFormat(): - message.data.toDestinationPayloadFormat() -> string or - bytes - - - Converts the message data to the destination payload - format specified in - Pipeline.Destination.output_payload_format - - This function is meant to be applied to the - message.data field. - - If the destination payload format is not set, the - function will return the message data unchanged. - - - toCloudEventJsonWithPayloadFormat: - message.toCloudEventJsonWithPayloadFormat() -> map - - - Converts a message to the corresponding structure of - JSON format for CloudEvents - - This function applies toDestinationPayloadFormat() to - the message data. It also sets the corresponding - datacontenttype of the CloudEvent, as indicated by - Pipeline.Destination.output_payload_format. If no - output_payload_format is set it will use the existing - datacontenttype on the CloudEvent if present, else - leave datacontenttype absent. - - This function expects that the content of the message - will adhere to the standard CloudEvent format. If it - doesn’t then this function will fail. - - The result is a CEL map that corresponds to the JSON - representation of the CloudEvent. To convert that data - to a JSON string it can be chained with the - toJsonString function. - - The Pipeline expects that the message it receives adheres to - the standard CloudEvent format. If it doesn’t then the - outgoing message request may fail with a persistent error. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - message_binding_template: str = proto.Field( - proto.STRING, - number=3, - ) - - class AuthenticationConfig(proto.Message): - r"""Represents a config used to authenticate message requests. - - 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: - google_oidc (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OidcToken): - Optional. This authenticate method will apply - Google OIDC tokens signed by a GCP service - account to the requests. - - This field is a member of `oneof`_ ``authentication_method_descriptor``. - oauth_token (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OAuthToken): - Optional. If specified, an `OAuth - token `__ - will be generated and attached as an ``Authorization`` - header in the HTTP request. - - This type of authorization should generally only be used - when calling Google APIs hosted on \*.googleapis.com. - - This field is a member of `oneof`_ ``authentication_method_descriptor``. - """ - - class OidcToken(proto.Message): - r"""Represents a config used to authenticate with a Google OIDC - token using a GCP service account. Use this authentication - method to invoke your Cloud Run and Cloud Functions destinations - or HTTP endpoints that support Google OIDC. - - Attributes: - service_account (str): - Required. Service account email used to generate the OIDC - Token. The principal who calls this API must have - iam.serviceAccounts.actAs permission in the service account. - See - https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common - for more information. Eventarc service agents must have - roles/roles/iam.serviceAccountTokenCreator role to allow the - Pipeline to create OpenID tokens for authenticated requests. - audience (str): - Optional. Audience to be used to generate the - OIDC Token. The audience claim identifies the - recipient that the JWT is intended for. If - unspecified, the destination URI will be used. - """ - - service_account: str = proto.Field( - proto.STRING, - number=1, - ) - audience: str = proto.Field( - proto.STRING, - number=2, - ) - - class OAuthToken(proto.Message): - r"""Contains information needed for generating an `OAuth - token `__. - This type of authorization should generally only be used when - calling Google APIs hosted on \*.googleapis.com. - - Attributes: - service_account (str): - Required. Service account email used to generate the `OAuth - token `__. - The principal who calls this API must have - iam.serviceAccounts.actAs permission in the service account. - See - https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common - for more information. Eventarc service agents must have - roles/roles/iam.serviceAccountTokenCreator role to allow - Pipeline to create OAuth2 tokens for authenticated requests. - scope (str): - Optional. OAuth scope to be used for - generating OAuth access token. If not specified, - "https://www.googleapis.com/auth/cloud-platform" - will be used. - """ - - service_account: str = proto.Field( - proto.STRING, - number=1, - ) - scope: str = proto.Field( - proto.STRING, - number=2, - ) - - google_oidc: 'Pipeline.Destination.AuthenticationConfig.OidcToken' = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication_method_descriptor', - message='Pipeline.Destination.AuthenticationConfig.OidcToken', - ) - oauth_token: 'Pipeline.Destination.AuthenticationConfig.OAuthToken' = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication_method_descriptor', - message='Pipeline.Destination.AuthenticationConfig.OAuthToken', - ) - - network_config: 'Pipeline.Destination.NetworkConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='Pipeline.Destination.NetworkConfig', - ) - http_endpoint: 'Pipeline.Destination.HttpEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='destination_descriptor', - message='Pipeline.Destination.HttpEndpoint', - ) - workflow: str = proto.Field( - proto.STRING, - number=3, - oneof='destination_descriptor', - ) - message_bus: str = proto.Field( - proto.STRING, - number=4, - oneof='destination_descriptor', - ) - topic: str = proto.Field( - proto.STRING, - number=8, - oneof='destination_descriptor', - ) - authentication_config: 'Pipeline.Destination.AuthenticationConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='Pipeline.Destination.AuthenticationConfig', - ) - output_payload_format: 'Pipeline.MessagePayloadFormat' = proto.Field( - proto.MESSAGE, - number=6, - message='Pipeline.MessagePayloadFormat', - ) - - class Mediation(proto.Message): - r"""Mediation defines different ways to modify the Pipeline. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - transformation (google.cloud.eventarc_v1.types.Pipeline.Mediation.Transformation): - Optional. How the Pipeline is to transform - messages - - This field is a member of `oneof`_ ``mediation_descriptor``. - """ - - class Transformation(proto.Message): - r"""Transformation defines the way to transform an incoming - message. - - Attributes: - transformation_template (str): - Optional. The CEL expression template to apply to transform - messages. The following CEL extension functions are provided - for use in this CEL expression: - - - merge: map1.merge(map2) -> map3 - - - Merges the passed CEL map with the existing CEL map - the function is applied to. - - If the same key exists in both maps, if the key's - value is type map both maps are merged else the value - from the passed map is used. - - - denormalize: map.denormalize() -> map - - - Denormalizes a CEL map such that every value of type - map or key in the map is expanded to return a single - level map. - - The resulting keys are "." separated indices of the - map keys. - - For example: { "a": 1, "b": { "c": 2, "d": 3 } "e": - [4, 5] } .denormalize() -> { "a": 1, "b.c": 2, "b.d": - 3, "e.0": 4, "e.1": 5 } - - - setField: map.setField(key, value) -> message - - - Sets the field of the message with the given key to - the given value. - - If the field is not present it will be added. - - If the field is present it will be overwritten. - - The key can be a dot separated path to set a field in - a nested message. - - Key must be of type string. - - Value may be any valid type. - - - removeFields: map.removeFields([key1, key2, ...]) -> - message - - - Removes the fields of the map with the given keys. - - The keys can be a dot separated path to remove a field - in a nested message. - - If a key is not found it will be ignored. - - Keys must be of type string. - - - toMap: [map1, map2, ...].toMap() -> map - - - Converts a CEL list of CEL maps to a single CEL map - - - toDestinationPayloadFormat(): - message.data.toDestinationPayloadFormat() -> string or - bytes - - - Converts the message data to the destination payload - format specified in - Pipeline.Destination.output_payload_format - - This function is meant to be applied to the - message.data field. - - If the destination payload format is not set, the - function will return the message data unchanged. - - - toCloudEventJsonWithPayloadFormat: - message.toCloudEventJsonWithPayloadFormat() -> map - - - Converts a message to the corresponding structure of - JSON format for CloudEvents - - This function applies toDestinationPayloadFormat() to - the message data. It also sets the corresponding - datacontenttype of the CloudEvent, as indicated by - Pipeline.Destination.output_payload_format. If no - output_payload_format is set it will use the existing - datacontenttype on the CloudEvent if present, else - leave datacontenttype absent. - - This function expects that the content of the message - will adhere to the standard CloudEvent format. If it - doesn’t then this function will fail. - - The result is a CEL map that corresponds to the JSON - representation of the CloudEvent. To convert that data - to a JSON string it can be chained with the - toJsonString function. - """ - - transformation_template: str = proto.Field( - proto.STRING, - number=1, - ) - - transformation: 'Pipeline.Mediation.Transformation' = proto.Field( - proto.MESSAGE, - number=1, - oneof='mediation_descriptor', - message='Pipeline.Mediation.Transformation', - ) - - class RetryPolicy(proto.Message): - r"""The retry policy configuration for the Pipeline. The pipeline - exponentially backs off in case the destination is non responsive or - returns a retryable error code. The default semantics are as - follows: The backoff starts with a 5 second delay and doubles the - delay after each failed attempt (10 seconds, 20 seconds, 40 seconds, - etc.). The delay is capped at 60 seconds by default. Please note - that if you set the min_retry_delay and max_retry_delay fields to - the same value this will make the duration between retries constant. - - Attributes: - max_attempts (int): - Optional. The maximum number of delivery - attempts for any message. The value must be - between 1 and 100. The default value for this - field is 5. - min_retry_delay (google.protobuf.duration_pb2.Duration): - Optional. The minimum amount of seconds to - wait between retry attempts. The value must be - between 1 and 600. The default value for this - field is 5. - max_retry_delay (google.protobuf.duration_pb2.Duration): - Optional. The maximum amount of seconds to - wait between retry attempts. The value must be - between 1 and 600. The default value for this - field is 60. - """ - - max_attempts: int = proto.Field( - proto.INT32, - number=1, - ) - min_retry_delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - max_retry_delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - uid: str = proto.Field( - proto.STRING, - number=5, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - display_name: str = proto.Field( - proto.STRING, - number=7, - ) - destinations: MutableSequence[Destination] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=Destination, - ) - mediations: MutableSequence[Mediation] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=Mediation, - ) - crypto_key_name: str = proto.Field( - proto.STRING, - number=10, - ) - input_payload_format: MessagePayloadFormat = proto.Field( - proto.MESSAGE, - number=11, - message=MessagePayloadFormat, - ) - logging_config: gce_logging_config.LoggingConfig = proto.Field( - proto.MESSAGE, - number=12, - message=gce_logging_config.LoggingConfig, - ) - retry_policy: RetryPolicy = proto.Field( - proto.MESSAGE, - number=13, - message=RetryPolicy, - ) - etag: str = proto.Field( - proto.STRING, - number=99, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py b/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py deleted file mode 100644 index 68e45d11944f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/google/cloud/eventarc_v1/types/trigger.py +++ /dev/null @@ -1,489 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.eventarc_v1.types import network_config as gce_network_config -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import code_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.eventarc.v1', - manifest={ - 'Trigger', - 'EventFilter', - 'StateCondition', - 'Destination', - 'Transport', - 'CloudRun', - 'GKE', - 'Pubsub', - 'HttpEndpoint', - }, -) - - -class Trigger(proto.Message): - r"""A representation of the trigger resource. - - Attributes: - name (str): - Required. The resource name of the trigger. Must be unique - within the location of the project and must be in - ``projects/{project}/locations/{location}/triggers/{trigger}`` - format. - 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. - 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. - event_filters (MutableSequence[google.cloud.eventarc_v1.types.EventFilter]): - Required. Unordered list. The list of filters - that applies to event attributes. Only events - that match all the provided filters are sent to - the destination. - service_account (str): - Optional. The IAM service account email associated with the - trigger. The service account represents the identity of the - trigger. - - The ``iam.serviceAccounts.actAs`` permission must be granted - on the service account to allow a principal to impersonate - the service account. For more information, see the `Roles - and permissions `__ - page specific to the trigger destination. - destination (google.cloud.eventarc_v1.types.Destination): - Required. Destination specifies where the - events should be sent to. - transport (google.cloud.eventarc_v1.types.Transport): - Optional. To deliver messages, Eventarc might - use other Google Cloud products as a transport - intermediary. This field contains a reference to - that transport intermediary. This information - can be used for debugging purposes. - labels (MutableMapping[str, str]): - Optional. User labels attached to the - triggers that can be used to group resources. - channel (str): - Optional. The name of the channel associated with the - trigger in - ``projects/{project}/locations/{location}/channels/{channel}`` - format. You must provide a channel to receive events from - Eventarc SaaS partners. - conditions (MutableMapping[str, google.cloud.eventarc_v1.types.StateCondition]): - Output only. The reason(s) why a trigger is - in FAILED state. - event_data_content_type (str): - Optional. EventDataContentType specifies the type of payload - in MIME format that is expected from the CloudEvent data - field. This is set to ``application/json`` if the value is - not defined. - satisfies_pzs (bool): - Output only. Whether or not this Trigger - satisfies the requirements of physical zone - separation - etag (str): - Output only. This checksum is computed by the - server based on the value of other fields, and - might be sent only on create requests to ensure - that the client has an up-to-date value before - proceeding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uid: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - event_filters: MutableSequence['EventFilter'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='EventFilter', - ) - service_account: str = proto.Field( - proto.STRING, - number=9, - ) - destination: 'Destination' = proto.Field( - proto.MESSAGE, - number=10, - message='Destination', - ) - transport: 'Transport' = proto.Field( - proto.MESSAGE, - number=11, - message='Transport', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - channel: str = proto.Field( - proto.STRING, - number=13, - ) - conditions: MutableMapping[str, 'StateCondition'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=15, - message='StateCondition', - ) - event_data_content_type: str = proto.Field( - proto.STRING, - number=16, - ) - satisfies_pzs: bool = proto.Field( - proto.BOOL, - number=19, - ) - etag: str = proto.Field( - proto.STRING, - number=99, - ) - - -class EventFilter(proto.Message): - r"""Filters events based on exact matches on the CloudEvents - attributes. - - Attributes: - attribute (str): - Required. The name of a CloudEvents attribute. Currently, - only a subset of attributes are supported for filtering. You - can `retrieve a specific provider's supported event - types `__. - - All triggers MUST provide a filter for the 'type' attribute. - value (str): - Required. The value for the attribute. - operator (str): - Optional. The operator used for matching the events with the - value of the filter. If not specified, only events that have - an exact key-value pair specified in the filter are matched. - The allowed values are ``path_pattern`` and - ``match-path-pattern``. ``path_pattern`` is only allowed for - GCFv1 triggers. - """ - - attribute: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - operator: str = proto.Field( - proto.STRING, - number=3, - ) - - -class StateCondition(proto.Message): - r"""A condition that is part of the trigger state computation. - - Attributes: - code (google.rpc.code_pb2.Code): - The canonical code of the condition. - message (str): - Human-readable message. - """ - - code: code_pb2.Code = proto.Field( - proto.ENUM, - number=1, - enum=code_pb2.Code, - ) - message: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Destination(proto.Message): - r"""Represents a target of an invocation over HTTP. - - 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: - cloud_run (google.cloud.eventarc_v1.types.CloudRun): - Cloud Run fully-managed resource that - receives the events. The resource should be in - the same project as the trigger. - - This field is a member of `oneof`_ ``descriptor``. - cloud_function (str): - The Cloud Function resource name. Cloud Functions V1 and V2 - are supported. Format: - ``projects/{project}/locations/{location}/functions/{function}`` - - This is a read-only field. Creating Cloud Functions V1/V2 - triggers is only supported via the Cloud Functions product. - An error will be returned if the user sets this value. - - This field is a member of `oneof`_ ``descriptor``. - gke (google.cloud.eventarc_v1.types.GKE): - A GKE service capable of receiving events. - The service should be running in the same - project as the trigger. - - This field is a member of `oneof`_ ``descriptor``. - workflow (str): - The resource name of the Workflow whose Executions are - triggered by the events. The Workflow resource should be - deployed in the same project as the trigger. Format: - ``projects/{project}/locations/{location}/workflows/{workflow}`` - - This field is a member of `oneof`_ ``descriptor``. - http_endpoint (google.cloud.eventarc_v1.types.HttpEndpoint): - An HTTP endpoint destination described by an - URI. - - This field is a member of `oneof`_ ``descriptor``. - network_config (google.cloud.eventarc_v1.types.NetworkConfig): - Optional. Network config is used to configure - how Eventarc resolves and connect to a - destination. This should only be used with - HttpEndpoint destination type. - """ - - cloud_run: 'CloudRun' = proto.Field( - proto.MESSAGE, - number=1, - oneof='descriptor', - message='CloudRun', - ) - cloud_function: str = proto.Field( - proto.STRING, - number=2, - oneof='descriptor', - ) - gke: 'GKE' = proto.Field( - proto.MESSAGE, - number=3, - oneof='descriptor', - message='GKE', - ) - workflow: str = proto.Field( - proto.STRING, - number=4, - oneof='descriptor', - ) - http_endpoint: 'HttpEndpoint' = proto.Field( - proto.MESSAGE, - number=5, - oneof='descriptor', - message='HttpEndpoint', - ) - network_config: gce_network_config.NetworkConfig = proto.Field( - proto.MESSAGE, - number=6, - message=gce_network_config.NetworkConfig, - ) - - -class Transport(proto.Message): - r"""Represents the transport intermediaries created for the - trigger to deliver events. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - pubsub (google.cloud.eventarc_v1.types.Pubsub): - The Pub/Sub topic and subscription used by - Eventarc as a transport intermediary. - - This field is a member of `oneof`_ ``intermediary``. - """ - - pubsub: 'Pubsub' = proto.Field( - proto.MESSAGE, - number=1, - oneof='intermediary', - message='Pubsub', - ) - - -class CloudRun(proto.Message): - r"""Represents a Cloud Run destination. - - Attributes: - service (str): - Required. The name of the Cloud Run service - being addressed. See - https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services. - - Only services located in the same project as the - trigger object can be addressed. - path (str): - Optional. The relative path on the Cloud Run - service the events should be sent to. - - The value must conform to the definition of a - URI path segment (section 3.3 of RFC2396). - Examples: "/route", "route", "route/subroute". - region (str): - Required. The region the Cloud Run service is - deployed in. - """ - - service: str = proto.Field( - proto.STRING, - number=1, - ) - path: str = proto.Field( - proto.STRING, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GKE(proto.Message): - r"""Represents a GKE destination. - - Attributes: - cluster (str): - Required. The name of the cluster the GKE - service is running in. The cluster must be - running in the same project as the trigger being - created. - location (str): - Required. The name of the Google Compute - Engine in which the cluster resides, which can - either be compute zone (for example, - us-central1-a) for the zonal clusters or region - (for example, us-central1) for regional - clusters. - namespace (str): - Required. The namespace the GKE service is - running in. - service (str): - Required. Name of the GKE service. - path (str): - Optional. The relative path on the GKE - service the events should be sent to. - - The value must conform to the definition of a - URI path segment (section 3.3 of RFC2396). - Examples: "/route", "route", "route/subroute". - """ - - cluster: str = proto.Field( - proto.STRING, - number=1, - ) - location: str = proto.Field( - proto.STRING, - number=2, - ) - namespace: str = proto.Field( - proto.STRING, - number=3, - ) - service: str = proto.Field( - proto.STRING, - number=4, - ) - path: str = proto.Field( - proto.STRING, - number=5, - ) - - -class Pubsub(proto.Message): - r"""Represents a Pub/Sub transport. - - Attributes: - topic (str): - Optional. The name of the Pub/Sub topic created and managed - by Eventarc as a transport for the event delivery. Format: - ``projects/{PROJECT_ID}/topics/{TOPIC_NAME}``. - - You can set an existing topic for triggers of the type - ``google.cloud.pubsub.topic.v1.messagePublished``. The topic - you provide here is not deleted by Eventarc at trigger - deletion. - subscription (str): - Output only. The name of the Pub/Sub subscription created - and managed by Eventarc as a transport for the event - delivery. Format: - ``projects/{PROJECT_ID}/subscriptions/{SUBSCRIPTION_NAME}``. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - subscription: str = proto.Field( - proto.STRING, - number=2, - ) - - -class HttpEndpoint(proto.Message): - r"""Represents a HTTP endpoint destination. - - Attributes: - uri (str): - Required. The URI of the HTTP enpdoint. - - The value must be a RFC2396 URI string. Examples: - ``http://10.10.10.8:80/route``, - ``http://svc.us-central1.p.local:8080/``. Only HTTP and - HTTPS protocols are supported. The host can be either a - static IP addressable from the VPC specified by the network - config, or an internal DNS hostname of the service - resolvable via Cloud DNS. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/mypy.ini b/owl-bot-staging/google-cloud-eventarc/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-eventarc/v1/noxfile.py b/owl-bot-staging/google-cloud-eventarc/v1/noxfile.py deleted file mode 100644 index 685faed09bd5..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-eventarc' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/eventarc_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/eventarc_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py deleted file mode 100644 index ebff0154f662..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateChannel_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 eventarc_v1 - - -async def sample_create_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - channel = eventarc_v1.Channel() - channel.pubsub_topic = "pubsub_topic_value" - channel.name = "name_value" - - request = eventarc_v1.CreateChannelRequest( - parent="parent_value", - channel=channel, - channel_id="channel_id_value", - ) - - # Make the request - operation = client.create_channel(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py deleted file mode 100644 index 27908ff206e8..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateChannelConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateChannelConnection_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 eventarc_v1 - - -async def sample_create_channel_connection(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - channel_connection = eventarc_v1.ChannelConnection() - channel_connection.name = "name_value" - channel_connection.channel = "channel_value" - - request = eventarc_v1.CreateChannelConnectionRequest( - parent="parent_value", - channel_connection=channel_connection, - channel_connection_id="channel_connection_id_value", - ) - - # Make the request - operation = client.create_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateChannelConnection_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py deleted file mode 100644 index a4d3d5321f73..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_connection_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateChannelConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateChannelConnection_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 eventarc_v1 - - -def sample_create_channel_connection(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - channel_connection = eventarc_v1.ChannelConnection() - channel_connection.name = "name_value" - channel_connection.channel = "channel_value" - - request = eventarc_v1.CreateChannelConnectionRequest( - parent="parent_value", - channel_connection=channel_connection, - channel_connection_id="channel_connection_id_value", - ) - - # Make the request - operation = client.create_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateChannelConnection_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py deleted file mode 100644 index de1b27e29efa..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateChannel_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 eventarc_v1 - - -def sample_create_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - channel = eventarc_v1.Channel() - channel.pubsub_topic = "pubsub_topic_value" - channel.name = "name_value" - - request = eventarc_v1.CreateChannelRequest( - parent="parent_value", - channel=channel, - channel_id="channel_id_value", - ) - - # Make the request - operation = client.create_channel(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py deleted file mode 100644 index 7b835166e5af..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateEnrollment_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 eventarc_v1 - - -async def sample_create_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.CreateEnrollmentRequest( - parent="parent_value", - enrollment=enrollment, - enrollment_id="enrollment_id_value", - ) - - # Make the request - operation = client.create_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py deleted file mode 100644 index 01f0e1796c2a..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateEnrollment_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 eventarc_v1 - - -def sample_create_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.CreateEnrollmentRequest( - parent="parent_value", - enrollment=enrollment, - enrollment_id="enrollment_id_value", - ) - - # Make the request - operation = client.create_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py deleted file mode 100644 index 7499aa595d93..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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 eventarc_v1 - - -async def sample_create_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.CreateGoogleApiSourceRequest( - parent="parent_value", - google_api_source=google_api_source, - google_api_source_id="google_api_source_id_value", - ) - - # Make the request - operation = client.create_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py deleted file mode 100644 index 43c341d99c69..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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 eventarc_v1 - - -def sample_create_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.CreateGoogleApiSourceRequest( - parent="parent_value", - google_api_source=google_api_source, - google_api_source_id="google_api_source_id_value", - ) - - # Make the request - operation = client.create_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py deleted file mode 100644 index a36aac63a329..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateMessageBus_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 eventarc_v1 - - -async def sample_create_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.CreateMessageBusRequest( - parent="parent_value", - message_bus_id="message_bus_id_value", - ) - - # Make the request - operation = client.create_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py deleted file mode 100644 index c57422a9805b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateMessageBus_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 eventarc_v1 - - -def sample_create_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.CreateMessageBusRequest( - parent="parent_value", - message_bus_id="message_bus_id_value", - ) - - # Make the request - operation = client.create_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py deleted file mode 100644 index 98e5c2bb46dc..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreatePipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreatePipeline_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 eventarc_v1 - - -async def sample_create_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.CreatePipelineRequest( - parent="parent_value", - pipeline=pipeline, - pipeline_id="pipeline_id_value", - ) - - # Make the request - operation = client.create_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreatePipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py deleted file mode 100644 index 322d5cc27373..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreatePipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreatePipeline_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 eventarc_v1 - - -def sample_create_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.CreatePipelineRequest( - parent="parent_value", - pipeline=pipeline, - pipeline_id="pipeline_id_value", - ) - - # Make the request - operation = client.create_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreatePipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py deleted file mode 100644 index 441e73fc34c3..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateTrigger_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 eventarc_v1 - - -async def sample_create_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - trigger = eventarc_v1.Trigger() - trigger.name = "name_value" - trigger.event_filters.attribute = "attribute_value" - trigger.event_filters.value = "value_value" - trigger.destination.cloud_run.service = "service_value" - trigger.destination.cloud_run.region = "region_value" - - request = eventarc_v1.CreateTriggerRequest( - parent="parent_value", - trigger=trigger, - trigger_id="trigger_id_value", - ) - - # Make the request - operation = client.create_trigger(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py deleted file mode 100644 index 10b2fb5c6f95..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_CreateTrigger_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 eventarc_v1 - - -def sample_create_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - trigger = eventarc_v1.Trigger() - trigger.name = "name_value" - trigger.event_filters.attribute = "attribute_value" - trigger.event_filters.value = "value_value" - trigger.destination.cloud_run.service = "service_value" - trigger.destination.cloud_run.region = "region_value" - - request = eventarc_v1.CreateTriggerRequest( - parent="parent_value", - trigger=trigger, - trigger_id="trigger_id_value", - ) - - # Make the request - operation = client.create_trigger(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_CreateTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py deleted file mode 100644 index 9b4f036e29e2..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteChannel_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 eventarc_v1 - - -async def sample_delete_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py deleted file mode 100644 index 92f3c64550fd..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteChannelConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteChannelConnection_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 eventarc_v1 - - -async def sample_delete_channel_connection(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteChannelConnection_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py deleted file mode 100644 index c9a0a1e35252..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_connection_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteChannelConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteChannelConnection_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 eventarc_v1 - - -def sample_delete_channel_connection(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteChannelConnection_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py deleted file mode 100644 index eea3bbe17056..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteChannel_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 eventarc_v1 - - -def sample_delete_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteChannelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_channel(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py deleted file mode 100644 index 1452377cf60d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteEnrollment_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 eventarc_v1 - - -async def sample_delete_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteEnrollmentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py deleted file mode 100644 index 85644a33732f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteEnrollment_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 eventarc_v1 - - -def sample_delete_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteEnrollmentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py deleted file mode 100644 index 233bc8f978bc..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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 eventarc_v1 - - -async def sample_delete_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py deleted file mode 100644 index 5036193f8da4..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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 eventarc_v1 - - -def sample_delete_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py deleted file mode 100644 index a9c638e332f0..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteMessageBus_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 eventarc_v1 - - -async def sample_delete_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteMessageBusRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py deleted file mode 100644 index 2d73c87e36c1..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteMessageBus_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 eventarc_v1 - - -def sample_delete_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteMessageBusRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py deleted file mode 100644 index 01ad54b6a7bb..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeletePipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeletePipeline_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 eventarc_v1 - - -async def sample_delete_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeletePipelineRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeletePipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py deleted file mode 100644 index a74533f9472e..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeletePipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeletePipeline_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 eventarc_v1 - - -def sample_delete_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeletePipelineRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeletePipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py deleted file mode 100644 index d8b0a8c4ca2c..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteTrigger_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 eventarc_v1 - - -async def sample_delete_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteTriggerRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_trigger(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py deleted file mode 100644 index 50ce9d7741ac..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_DeleteTrigger_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 eventarc_v1 - - -def sample_delete_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.DeleteTriggerRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_trigger(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_DeleteTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py deleted file mode 100644 index a2bdc034a30d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetChannel_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 eventarc_v1 - - -async def sample_get_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelRequest( - name="name_value", - ) - - # Make the request - response = await client.get_channel(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py deleted file mode 100644 index d1f83e2be2ff..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetChannelConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetChannelConnection_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 eventarc_v1 - - -async def sample_get_channel_connection(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelConnectionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_channel_connection(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetChannelConnection_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py deleted file mode 100644 index e91dfb82ba94..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_connection_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetChannelConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetChannelConnection_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 eventarc_v1 - - -def sample_get_channel_connection(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelConnectionRequest( - name="name_value", - ) - - # Make the request - response = client.get_channel_connection(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetChannelConnection_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py deleted file mode 100644 index 24f6e592ab2a..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_channel_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetChannel_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 eventarc_v1 - - -def sample_get_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetChannelRequest( - name="name_value", - ) - - # Make the request - response = client.get_channel(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py deleted file mode 100644 index 60b53a3c1f60..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetEnrollment_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 eventarc_v1 - - -async def sample_get_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetEnrollmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_enrollment(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py deleted file mode 100644 index 5e5cfe0be1d3..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetEnrollment_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 eventarc_v1 - - -def sample_get_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetEnrollmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_enrollment(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py deleted file mode 100644 index 4d6e6a7271d0..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetGoogleApiSource_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 eventarc_v1 - - -async def sample_get_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_google_api_source(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py deleted file mode 100644 index d48db32727b5..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetGoogleApiSource_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 eventarc_v1 - - -def sample_get_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleApiSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_google_api_source(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py deleted file mode 100644 index 43968fed3093..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGoogleChannelConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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 eventarc_v1 - - -async def sample_get_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleChannelConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_google_channel_config(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py deleted file mode 100644 index 87cb63ab4e1f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_channel_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetGoogleChannelConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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 eventarc_v1 - - -def sample_get_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetGoogleChannelConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_google_channel_config(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py deleted file mode 100644 index f6fa28cec89e..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetMessageBus_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 eventarc_v1 - - -async def sample_get_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetMessageBusRequest( - name="name_value", - ) - - # Make the request - response = await client.get_message_bus(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py deleted file mode 100644 index f973b30f58a0..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetMessageBus_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 eventarc_v1 - - -def sample_get_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetMessageBusRequest( - name="name_value", - ) - - # Make the request - response = client.get_message_bus(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py deleted file mode 100644 index 8b18437b7a6c..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetPipeline_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 eventarc_v1 - - -async def sample_get_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetPipelineRequest( - name="name_value", - ) - - # Make the request - response = await client.get_pipeline(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetPipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py deleted file mode 100644 index aaeabd978963..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetPipeline_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 eventarc_v1 - - -def sample_get_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetPipelineRequest( - name="name_value", - ) - - # Make the request - response = client.get_pipeline(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetPipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py deleted file mode 100644 index ee87d696f717..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProvider -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetProvider_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 eventarc_v1 - - -async def sample_get_provider(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetProviderRequest( - name="name_value", - ) - - # Make the request - response = await client.get_provider(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetProvider_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py deleted file mode 100644 index 9c19d1923ae4..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_provider_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProvider -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetProvider_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 eventarc_v1 - - -def sample_get_provider(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetProviderRequest( - name="name_value", - ) - - # Make the request - response = client.get_provider(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetProvider_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py deleted file mode 100644 index 36655bfbf3b6..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetTrigger_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 eventarc_v1 - - -async def sample_get_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.GetTriggerRequest( - name="name_value", - ) - - # Make the request - response = await client.get_trigger(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py deleted file mode 100644 index 8354eb167ebc..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_get_trigger_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_GetTrigger_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 eventarc_v1 - - -def sample_get_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.GetTriggerRequest( - name="name_value", - ) - - # Make the request - response = client.get_trigger(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_GetTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py deleted file mode 100644 index 24a4ac3b6b03..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListChannelConnections -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListChannelConnections_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 eventarc_v1 - - -async def sample_list_channel_connections(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channel_connections(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListChannelConnections_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py deleted file mode 100644 index a8a5ec2ab3fd..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channel_connections_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListChannelConnections -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListChannelConnections_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 eventarc_v1 - - -def sample_list_channel_connections(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channel_connections(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListChannelConnections_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py deleted file mode 100644 index cb70db05a623..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListChannels -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListChannels_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 eventarc_v1 - - -async def sample_list_channels(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channels(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListChannels_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py deleted file mode 100644 index 405dd6d39da9..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_channels_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListChannels -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListChannels_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 eventarc_v1 - - -def sample_list_channels(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListChannelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_channels(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListChannels_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py deleted file mode 100644 index a7b6705b45da..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEnrollments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListEnrollments_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 eventarc_v1 - - -async def sample_list_enrollments(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_enrollments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListEnrollments_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py deleted file mode 100644 index 98c3c91cfb59..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEnrollments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListEnrollments_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 eventarc_v1 - - -def sample_list_enrollments(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_enrollments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListEnrollments_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py deleted file mode 100644 index d5190ae8997a..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListGoogleApiSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListGoogleApiSources_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 eventarc_v1 - - -async def sample_list_google_api_sources(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListGoogleApiSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_google_api_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListGoogleApiSources_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py deleted file mode 100644 index d5148cefa663..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListGoogleApiSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListGoogleApiSources_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 eventarc_v1 - - -def sample_list_google_api_sources(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListGoogleApiSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_google_api_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListGoogleApiSources_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py deleted file mode 100644 index 43db0141b579..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessageBusEnrollments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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 eventarc_v1 - - -async def sample_list_message_bus_enrollments(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_bus_enrollments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py deleted file mode 100644 index 54bc9ecb400a..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessageBusEnrollments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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 eventarc_v1 - - -def sample_list_message_bus_enrollments(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusEnrollmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_bus_enrollments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py deleted file mode 100644 index 97f05e8fafa1..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessageBuses -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListMessageBuses_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 eventarc_v1 - - -async def sample_list_message_buses(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_buses(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListMessageBuses_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py deleted file mode 100644 index 1b41aa44c18f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessageBuses -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListMessageBuses_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 eventarc_v1 - - -def sample_list_message_buses(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListMessageBusesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_message_buses(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListMessageBuses_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py deleted file mode 100644 index cbcbffb7ce4b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListPipelines -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListPipelines_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 eventarc_v1 - - -async def sample_list_pipelines(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListPipelinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_pipelines(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListPipelines_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py deleted file mode 100644 index 7b1bcff80a83..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListPipelines -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListPipelines_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 eventarc_v1 - - -def sample_list_pipelines(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListPipelinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_pipelines(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListPipelines_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py deleted file mode 100644 index 9b1a282ece1f..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProviders -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListProviders_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 eventarc_v1 - - -async def sample_list_providers(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_providers(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListProviders_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py deleted file mode 100644 index bcaaa019d697..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_providers_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProviders -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListProviders_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 eventarc_v1 - - -def sample_list_providers(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_providers(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListProviders_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py deleted file mode 100644 index 9878997a7732..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTriggers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListTriggers_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 eventarc_v1 - - -async def sample_list_triggers(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.ListTriggersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_triggers(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListTriggers_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py deleted file mode 100644 index 31558bea7a97..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_list_triggers_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTriggers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_ListTriggers_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 eventarc_v1 - - -def sample_list_triggers(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.ListTriggersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_triggers(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END eventarc_v1_generated_Eventarc_ListTriggers_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py deleted file mode 100644 index 7e7c83e81fb7..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateChannel_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 eventarc_v1 - - -async def sample_update_channel(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateChannelRequest( - ) - - # Make the request - operation = client.update_channel(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateChannel_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py deleted file mode 100644 index 8aaa9399228b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateChannel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateChannel_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 eventarc_v1 - - -def sample_update_channel(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateChannelRequest( - ) - - # Make the request - operation = client.update_channel(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateChannel_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py deleted file mode 100644 index a2aff56a7155..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateEnrollment_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 eventarc_v1 - - -async def sample_update_enrollment(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.UpdateEnrollmentRequest( - enrollment=enrollment, - ) - - # Make the request - operation = client.update_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateEnrollment_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py deleted file mode 100644 index ca7e0c563a30..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEnrollment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateEnrollment_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 eventarc_v1 - - -def sample_update_enrollment(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - enrollment = eventarc_v1.Enrollment() - enrollment.cel_match = "cel_match_value" - enrollment.message_bus = "message_bus_value" - enrollment.destination = "destination_value" - - request = eventarc_v1.UpdateEnrollmentRequest( - enrollment=enrollment, - ) - - # Make the request - operation = client.update_enrollment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateEnrollment_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py deleted file mode 100644 index 68a50c679ac3..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_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 eventarc_v1 - - -async def sample_update_google_api_source(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.UpdateGoogleApiSourceRequest( - google_api_source=google_api_source, - ) - - # Make the request - operation = client.update_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py deleted file mode 100644 index eea3efe7aa5b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGoogleApiSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_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 eventarc_v1 - - -def sample_update_google_api_source(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - google_api_source = eventarc_v1.GoogleApiSource() - google_api_source.destination = "destination_value" - - request = eventarc_v1.UpdateGoogleApiSourceRequest( - google_api_source=google_api_source, - ) - - # Make the request - operation = client.update_google_api_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py deleted file mode 100644 index ef74cb1afd0b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGoogleChannelConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_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 eventarc_v1 - - -async def sample_update_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - google_channel_config = eventarc_v1.GoogleChannelConfig() - google_channel_config.name = "name_value" - - request = eventarc_v1.UpdateGoogleChannelConfigRequest( - google_channel_config=google_channel_config, - ) - - # Make the request - response = await client.update_google_channel_config(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py deleted file mode 100644 index d20d7c495395..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_channel_config_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateGoogleChannelConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_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 eventarc_v1 - - -def sample_update_google_channel_config(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - google_channel_config = eventarc_v1.GoogleChannelConfig() - google_channel_config.name = "name_value" - - request = eventarc_v1.UpdateGoogleChannelConfigRequest( - google_channel_config=google_channel_config, - ) - - # Make the request - response = client.update_google_channel_config(request=request) - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py deleted file mode 100644 index 3c1b9e888f72..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateMessageBus_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 eventarc_v1 - - -async def sample_update_message_bus(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateMessageBusRequest( - ) - - # Make the request - operation = client.update_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateMessageBus_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py deleted file mode 100644 index 6aa6cb75b8bd..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateMessageBus -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateMessageBus_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 eventarc_v1 - - -def sample_update_message_bus(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateMessageBusRequest( - ) - - # Make the request - operation = client.update_message_bus(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateMessageBus_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py deleted file mode 100644 index 76c6fed7750b..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdatePipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdatePipeline_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 eventarc_v1 - - -async def sample_update_pipeline(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.UpdatePipelineRequest( - pipeline=pipeline, - ) - - # Make the request - operation = client.update_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdatePipeline_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py deleted file mode 100644 index 2f70f5363ff2..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdatePipeline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdatePipeline_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 eventarc_v1 - - -def sample_update_pipeline(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - pipeline = eventarc_v1.Pipeline() - pipeline.destinations.http_endpoint.uri = "uri_value" - - request = eventarc_v1.UpdatePipelineRequest( - pipeline=pipeline, - ) - - # Make the request - operation = client.update_pipeline(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdatePipeline_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py deleted file mode 100644 index a1e9fd81ea67..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateTrigger_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 eventarc_v1 - - -async def sample_update_trigger(): - # Create a client - client = eventarc_v1.EventarcAsyncClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateTriggerRequest( - ) - - # Make the request - operation = client.update_trigger(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateTrigger_async] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py deleted file mode 100644 index ba49e673d74c..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTrigger -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-eventarc - - -# [START eventarc_v1_generated_Eventarc_UpdateTrigger_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 eventarc_v1 - - -def sample_update_trigger(): - # Create a client - client = eventarc_v1.EventarcClient() - - # Initialize request argument(s) - request = eventarc_v1.UpdateTriggerRequest( - ) - - # Make the request - operation = client.update_trigger(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END eventarc_v1_generated_Eventarc_UpdateTrigger_sync] diff --git a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json b/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json deleted file mode 100644 index c94a230c3122..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json +++ /dev/null @@ -1,6510 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.eventarc.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-eventarc", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_channel_connection", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannelConnection", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateChannelConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateChannelConnectionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "channel_connection", - "type": "google.cloud.eventarc_v1.types.ChannelConnection" - }, - { - "name": "channel_connection_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_channel_connection" - }, - "description": "Sample for CreateChannelConnection", - "file": "eventarc_v1_generated_eventarc_create_channel_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateChannelConnection_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_channel_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_channel_connection", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannelConnection", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateChannelConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateChannelConnectionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "channel_connection", - "type": "google.cloud.eventarc_v1.types.ChannelConnection" - }, - { - "name": "channel_connection_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_channel_connection" - }, - "description": "Sample for CreateChannelConnection", - "file": "eventarc_v1_generated_eventarc_create_channel_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateChannelConnection_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_channel_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateChannelRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "channel", - "type": "google.cloud.eventarc_v1.types.Channel" - }, - { - "name": "channel_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_channel" - }, - "description": "Sample for CreateChannel", - "file": "eventarc_v1_generated_eventarc_create_channel_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateChannel_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_channel_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateChannelRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "channel", - "type": "google.cloud.eventarc_v1.types.Channel" - }, - { - "name": "channel_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_channel" - }, - "description": "Sample for CreateChannel", - "file": "eventarc_v1_generated_eventarc_create_channel_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateChannel_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_channel_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateEnrollmentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "enrollment", - "type": "google.cloud.eventarc_v1.types.Enrollment" - }, - { - "name": "enrollment_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_enrollment" - }, - "description": "Sample for CreateEnrollment", - "file": "eventarc_v1_generated_eventarc_create_enrollment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateEnrollment_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_enrollment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateEnrollmentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "enrollment", - "type": "google.cloud.eventarc_v1.types.Enrollment" - }, - { - "name": "enrollment_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_enrollment" - }, - "description": "Sample for CreateEnrollment", - "file": "eventarc_v1_generated_eventarc_create_enrollment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateEnrollment_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_enrollment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "google_api_source", - "type": "google.cloud.eventarc_v1.types.GoogleApiSource" - }, - { - "name": "google_api_source_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_google_api_source" - }, - "description": "Sample for CreateGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_create_google_api_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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": "eventarc_v1_generated_eventarc_create_google_api_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "google_api_source", - "type": "google.cloud.eventarc_v1.types.GoogleApiSource" - }, - { - "name": "google_api_source_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_google_api_source" - }, - "description": "Sample for CreateGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_create_google_api_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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": "eventarc_v1_generated_eventarc_create_google_api_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateMessageBusRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "message_bus", - "type": "google.cloud.eventarc_v1.types.MessageBus" - }, - { - "name": "message_bus_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_message_bus" - }, - "description": "Sample for CreateMessageBus", - "file": "eventarc_v1_generated_eventarc_create_message_bus_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateMessageBus_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": "eventarc_v1_generated_eventarc_create_message_bus_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateMessageBusRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "message_bus", - "type": "google.cloud.eventarc_v1.types.MessageBus" - }, - { - "name": "message_bus_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_message_bus" - }, - "description": "Sample for CreateMessageBus", - "file": "eventarc_v1_generated_eventarc_create_message_bus_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateMessageBus_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": "eventarc_v1_generated_eventarc_create_message_bus_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreatePipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreatePipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreatePipelineRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "pipeline", - "type": "google.cloud.eventarc_v1.types.Pipeline" - }, - { - "name": "pipeline_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_pipeline" - }, - "description": "Sample for CreatePipeline", - "file": "eventarc_v1_generated_eventarc_create_pipeline_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreatePipeline_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": "eventarc_v1_generated_eventarc_create_pipeline_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreatePipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreatePipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreatePipelineRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "pipeline", - "type": "google.cloud.eventarc_v1.types.Pipeline" - }, - { - "name": "pipeline_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_pipeline" - }, - "description": "Sample for CreatePipeline", - "file": "eventarc_v1_generated_eventarc_create_pipeline_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreatePipeline_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": "eventarc_v1_generated_eventarc_create_pipeline_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "trigger", - "type": "google.cloud.eventarc_v1.types.Trigger" - }, - { - "name": "trigger_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_trigger" - }, - "description": "Sample for CreateTrigger", - "file": "eventarc_v1_generated_eventarc_create_trigger_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_trigger_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "CreateTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "trigger", - "type": "google.cloud.eventarc_v1.types.Trigger" - }, - { - "name": "trigger_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_trigger" - }, - "description": "Sample for CreateTrigger", - "file": "eventarc_v1_generated_eventarc_create_trigger_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_create_trigger_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel_connection", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteChannelConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_channel_connection" - }, - "description": "Sample for DeleteChannelConnection", - "file": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_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": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel_connection", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteChannelConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_channel_connection" - }, - "description": "Sample for DeleteChannelConnection", - "file": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_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": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_channel" - }, - "description": "Sample for DeleteChannel", - "file": "eventarc_v1_generated_eventarc_delete_channel_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_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": "eventarc_v1_generated_eventarc_delete_channel_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_channel" - }, - "description": "Sample for DeleteChannel", - "file": "eventarc_v1_generated_eventarc_delete_channel_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_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": "eventarc_v1_generated_eventarc_delete_channel_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteEnrollmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_enrollment" - }, - "description": "Sample for DeleteEnrollment", - "file": "eventarc_v1_generated_eventarc_delete_enrollment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteEnrollment_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": "eventarc_v1_generated_eventarc_delete_enrollment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteEnrollmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_enrollment" - }, - "description": "Sample for DeleteEnrollment", - "file": "eventarc_v1_generated_eventarc_delete_enrollment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteEnrollment_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": "eventarc_v1_generated_eventarc_delete_enrollment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_google_api_source" - }, - "description": "Sample for DeleteGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_delete_google_api_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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": "eventarc_v1_generated_eventarc_delete_google_api_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_google_api_source" - }, - "description": "Sample for DeleteGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_delete_google_api_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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": "eventarc_v1_generated_eventarc_delete_google_api_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteMessageBusRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_message_bus" - }, - "description": "Sample for DeleteMessageBus", - "file": "eventarc_v1_generated_eventarc_delete_message_bus_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteMessageBus_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": "eventarc_v1_generated_eventarc_delete_message_bus_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteMessageBusRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_message_bus" - }, - "description": "Sample for DeleteMessageBus", - "file": "eventarc_v1_generated_eventarc_delete_message_bus_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteMessageBus_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": "eventarc_v1_generated_eventarc_delete_message_bus_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeletePipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeletePipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeletePipelineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_pipeline" - }, - "description": "Sample for DeletePipeline", - "file": "eventarc_v1_generated_eventarc_delete_pipeline_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeletePipeline_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": "eventarc_v1_generated_eventarc_delete_pipeline_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeletePipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeletePipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeletePipelineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "etag", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_pipeline" - }, - "description": "Sample for DeletePipeline", - "file": "eventarc_v1_generated_eventarc_delete_pipeline_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeletePipeline_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": "eventarc_v1_generated_eventarc_delete_pipeline_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "allow_missing", - "type": "bool" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_trigger" - }, - "description": "Sample for DeleteTrigger", - "file": "eventarc_v1_generated_eventarc_delete_trigger_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_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": "eventarc_v1_generated_eventarc_delete_trigger_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "DeleteTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "allow_missing", - "type": "bool" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_trigger" - }, - "description": "Sample for DeleteTrigger", - "file": "eventarc_v1_generated_eventarc_delete_trigger_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_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": "eventarc_v1_generated_eventarc_delete_trigger_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel_connection", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetChannelConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", - "shortName": "get_channel_connection" - }, - "description": "Sample for GetChannelConnection", - "file": "eventarc_v1_generated_eventarc_get_channel_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_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": "eventarc_v1_generated_eventarc_get_channel_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel_connection", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetChannelConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", - "shortName": "get_channel_connection" - }, - "description": "Sample for GetChannelConnection", - "file": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_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": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Channel", - "shortName": "get_channel" - }, - "description": "Sample for GetChannel", - "file": "eventarc_v1_generated_eventarc_get_channel_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_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": "eventarc_v1_generated_eventarc_get_channel_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Channel", - "shortName": "get_channel" - }, - "description": "Sample for GetChannel", - "file": "eventarc_v1_generated_eventarc_get_channel_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_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": "eventarc_v1_generated_eventarc_get_channel_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetEnrollmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Enrollment", - "shortName": "get_enrollment" - }, - "description": "Sample for GetEnrollment", - "file": "eventarc_v1_generated_eventarc_get_enrollment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetEnrollment_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": "eventarc_v1_generated_eventarc_get_enrollment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetEnrollmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Enrollment", - "shortName": "get_enrollment" - }, - "description": "Sample for GetEnrollment", - "file": "eventarc_v1_generated_eventarc_get_enrollment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetEnrollment_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": "eventarc_v1_generated_eventarc_get_enrollment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.GoogleApiSource", - "shortName": "get_google_api_source" - }, - "description": "Sample for GetGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_get_google_api_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleApiSource_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": "eventarc_v1_generated_eventarc_get_google_api_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.GoogleApiSource", - "shortName": "get_google_api_source" - }, - "description": "Sample for GetGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_get_google_api_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleApiSource_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": "eventarc_v1_generated_eventarc_get_google_api_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_channel_config", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetGoogleChannelConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "get_google_channel_config" - }, - "description": "Sample for GetGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_channel_config", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetGoogleChannelConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "get_google_channel_config" - }, - "description": "Sample for GetGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetMessageBusRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.MessageBus", - "shortName": "get_message_bus" - }, - "description": "Sample for GetMessageBus", - "file": "eventarc_v1_generated_eventarc_get_message_bus_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetMessageBus_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": "eventarc_v1_generated_eventarc_get_message_bus_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetMessageBusRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.MessageBus", - "shortName": "get_message_bus" - }, - "description": "Sample for GetMessageBus", - "file": "eventarc_v1_generated_eventarc_get_message_bus_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetMessageBus_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": "eventarc_v1_generated_eventarc_get_message_bus_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetPipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetPipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetPipelineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Pipeline", - "shortName": "get_pipeline" - }, - "description": "Sample for GetPipeline", - "file": "eventarc_v1_generated_eventarc_get_pipeline_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetPipeline_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": "eventarc_v1_generated_eventarc_get_pipeline_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetPipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetPipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetPipelineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Pipeline", - "shortName": "get_pipeline" - }, - "description": "Sample for GetPipeline", - "file": "eventarc_v1_generated_eventarc_get_pipeline_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetPipeline_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": "eventarc_v1_generated_eventarc_get_pipeline_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_provider", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetProvider" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetProviderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Provider", - "shortName": "get_provider" - }, - "description": "Sample for GetProvider", - "file": "eventarc_v1_generated_eventarc_get_provider_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_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": "eventarc_v1_generated_eventarc_get_provider_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_provider", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetProvider" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetProviderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Provider", - "shortName": "get_provider" - }, - "description": "Sample for GetProvider", - "file": "eventarc_v1_generated_eventarc_get_provider_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_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": "eventarc_v1_generated_eventarc_get_provider_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Trigger", - "shortName": "get_trigger" - }, - "description": "Sample for GetTrigger", - "file": "eventarc_v1_generated_eventarc_get_trigger_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_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": "eventarc_v1_generated_eventarc_get_trigger_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "GetTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.Trigger", - "shortName": "get_trigger" - }, - "description": "Sample for GetTrigger", - "file": "eventarc_v1_generated_eventarc_get_trigger_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_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": "eventarc_v1_generated_eventarc_get_trigger_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channel_connections", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListChannelConnections" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsAsyncPager", - "shortName": "list_channel_connections" - }, - "description": "Sample for ListChannelConnections", - "file": "eventarc_v1_generated_eventarc_list_channel_connections_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_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": "eventarc_v1_generated_eventarc_list_channel_connections_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channel_connections", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListChannelConnections" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsPager", - "shortName": "list_channel_connections" - }, - "description": "Sample for ListChannelConnections", - "file": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_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": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channels", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListChannels" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsAsyncPager", - "shortName": "list_channels" - }, - "description": "Sample for ListChannels", - "file": "eventarc_v1_generated_eventarc_list_channels_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_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": "eventarc_v1_generated_eventarc_list_channels_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channels", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListChannels" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsPager", - "shortName": "list_channels" - }, - "description": "Sample for ListChannels", - "file": "eventarc_v1_generated_eventarc_list_channels_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_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": "eventarc_v1_generated_eventarc_list_channels_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_enrollments", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListEnrollments", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListEnrollments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListEnrollmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsAsyncPager", - "shortName": "list_enrollments" - }, - "description": "Sample for ListEnrollments", - "file": "eventarc_v1_generated_eventarc_list_enrollments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListEnrollments_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": "eventarc_v1_generated_eventarc_list_enrollments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_enrollments", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListEnrollments", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListEnrollments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListEnrollmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsPager", - "shortName": "list_enrollments" - }, - "description": "Sample for ListEnrollments", - "file": "eventarc_v1_generated_eventarc_list_enrollments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListEnrollments_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": "eventarc_v1_generated_eventarc_list_enrollments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_google_api_sources", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListGoogleApiSources", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListGoogleApiSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesAsyncPager", - "shortName": "list_google_api_sources" - }, - "description": "Sample for ListGoogleApiSources", - "file": "eventarc_v1_generated_eventarc_list_google_api_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListGoogleApiSources_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": "eventarc_v1_generated_eventarc_list_google_api_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_google_api_sources", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListGoogleApiSources", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListGoogleApiSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesPager", - "shortName": "list_google_api_sources" - }, - "description": "Sample for ListGoogleApiSources", - "file": "eventarc_v1_generated_eventarc_list_google_api_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListGoogleApiSources_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": "eventarc_v1_generated_eventarc_list_google_api_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_message_bus_enrollments", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBusEnrollments", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListMessageBusEnrollments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsAsyncPager", - "shortName": "list_message_bus_enrollments" - }, - "description": "Sample for ListMessageBusEnrollments", - "file": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_message_bus_enrollments", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBusEnrollments", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListMessageBusEnrollments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsPager", - "shortName": "list_message_bus_enrollments" - }, - "description": "Sample for ListMessageBusEnrollments", - "file": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_message_buses", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBuses", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListMessageBuses" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListMessageBusesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesAsyncPager", - "shortName": "list_message_buses" - }, - "description": "Sample for ListMessageBuses", - "file": "eventarc_v1_generated_eventarc_list_message_buses_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBuses_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": "eventarc_v1_generated_eventarc_list_message_buses_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_message_buses", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBuses", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListMessageBuses" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListMessageBusesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesPager", - "shortName": "list_message_buses" - }, - "description": "Sample for ListMessageBuses", - "file": "eventarc_v1_generated_eventarc_list_message_buses_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBuses_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": "eventarc_v1_generated_eventarc_list_message_buses_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_pipelines", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListPipelines", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListPipelines" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListPipelinesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesAsyncPager", - "shortName": "list_pipelines" - }, - "description": "Sample for ListPipelines", - "file": "eventarc_v1_generated_eventarc_list_pipelines_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListPipelines_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": "eventarc_v1_generated_eventarc_list_pipelines_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_pipelines", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListPipelines", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListPipelines" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListPipelinesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesPager", - "shortName": "list_pipelines" - }, - "description": "Sample for ListPipelines", - "file": "eventarc_v1_generated_eventarc_list_pipelines_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListPipelines_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": "eventarc_v1_generated_eventarc_list_pipelines_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_providers", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListProviders" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersAsyncPager", - "shortName": "list_providers" - }, - "description": "Sample for ListProviders", - "file": "eventarc_v1_generated_eventarc_list_providers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_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": "eventarc_v1_generated_eventarc_list_providers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_providers", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListProviders" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersPager", - "shortName": "list_providers" - }, - "description": "Sample for ListProviders", - "file": "eventarc_v1_generated_eventarc_list_providers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_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": "eventarc_v1_generated_eventarc_list_providers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_triggers", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListTriggers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersAsyncPager", - "shortName": "list_triggers" - }, - "description": "Sample for ListTriggers", - "file": "eventarc_v1_generated_eventarc_list_triggers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_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": "eventarc_v1_generated_eventarc_list_triggers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_triggers", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "ListTriggers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersPager", - "shortName": "list_triggers" - }, - "description": "Sample for ListTriggers", - "file": "eventarc_v1_generated_eventarc_list_triggers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_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": "eventarc_v1_generated_eventarc_list_triggers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" - }, - { - "name": "channel", - "type": "google.cloud.eventarc_v1.types.Channel" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_channel" - }, - "description": "Sample for UpdateChannel", - "file": "eventarc_v1_generated_eventarc_update_channel_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_channel_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_channel", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateChannel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" - }, - { - "name": "channel", - "type": "google.cloud.eventarc_v1.types.Channel" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_channel" - }, - "description": "Sample for UpdateChannel", - "file": "eventarc_v1_generated_eventarc_update_channel_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_channel_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateEnrollmentRequest" - }, - { - "name": "enrollment", - "type": "google.cloud.eventarc_v1.types.Enrollment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_enrollment" - }, - "description": "Sample for UpdateEnrollment", - "file": "eventarc_v1_generated_eventarc_update_enrollment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateEnrollment_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": "eventarc_v1_generated_eventarc_update_enrollment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_enrollment", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateEnrollment", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateEnrollment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateEnrollmentRequest" - }, - { - "name": "enrollment", - "type": "google.cloud.eventarc_v1.types.Enrollment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_enrollment" - }, - "description": "Sample for UpdateEnrollment", - "file": "eventarc_v1_generated_eventarc_update_enrollment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateEnrollment_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": "eventarc_v1_generated_eventarc_update_enrollment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest" - }, - { - "name": "google_api_source", - "type": "google.cloud.eventarc_v1.types.GoogleApiSource" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_google_api_source" - }, - "description": "Sample for UpdateGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_update_google_api_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_google_api_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_api_source", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleApiSource", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateGoogleApiSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest" - }, - { - "name": "google_api_source", - "type": "google.cloud.eventarc_v1.types.GoogleApiSource" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_google_api_source" - }, - "description": "Sample for UpdateGoogleApiSource", - "file": "eventarc_v1_generated_eventarc_update_google_api_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_google_api_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_channel_config", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateGoogleChannelConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" - }, - { - "name": "google_channel_config", - "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "update_google_channel_config" - }, - "description": "Sample for UpdateGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_channel_config", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateGoogleChannelConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" - }, - { - "name": "google_channel_config", - "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "update_google_channel_config" - }, - "description": "Sample for UpdateGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateMessageBusRequest" - }, - { - "name": "message_bus", - "type": "google.cloud.eventarc_v1.types.MessageBus" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_message_bus" - }, - "description": "Sample for UpdateMessageBus", - "file": "eventarc_v1_generated_eventarc_update_message_bus_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateMessageBus_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_message_bus_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_message_bus", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateMessageBus", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateMessageBus" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateMessageBusRequest" - }, - { - "name": "message_bus", - "type": "google.cloud.eventarc_v1.types.MessageBus" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_message_bus" - }, - "description": "Sample for UpdateMessageBus", - "file": "eventarc_v1_generated_eventarc_update_message_bus_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateMessageBus_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_message_bus_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdatePipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdatePipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdatePipelineRequest" - }, - { - "name": "pipeline", - "type": "google.cloud.eventarc_v1.types.Pipeline" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_pipeline" - }, - "description": "Sample for UpdatePipeline", - "file": "eventarc_v1_generated_eventarc_update_pipeline_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdatePipeline_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_pipeline_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_pipeline", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdatePipeline", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdatePipeline" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdatePipelineRequest" - }, - { - "name": "pipeline", - "type": "google.cloud.eventarc_v1.types.Pipeline" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_pipeline" - }, - "description": "Sample for UpdatePipeline", - "file": "eventarc_v1_generated_eventarc_update_pipeline_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdatePipeline_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_pipeline_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", - "shortName": "EventarcAsyncClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateTriggerRequest" - }, - { - "name": "trigger", - "type": "google.cloud.eventarc_v1.types.Trigger" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "allow_missing", - "type": "bool" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_trigger" - }, - "description": "Sample for UpdateTrigger", - "file": "eventarc_v1_generated_eventarc_update_trigger_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateTrigger_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_trigger_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.eventarc_v1.EventarcClient", - "shortName": "EventarcClient" - }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_trigger", - "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateTrigger", - "service": { - "fullName": "google.cloud.eventarc.v1.Eventarc", - "shortName": "Eventarc" - }, - "shortName": "UpdateTrigger" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateTriggerRequest" - }, - { - "name": "trigger", - "type": "google.cloud.eventarc_v1.types.Trigger" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "allow_missing", - "type": "bool" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_trigger" - }, - "description": "Sample for UpdateTrigger", - "file": "eventarc_v1_generated_eventarc_update_trigger_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateTrigger_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "eventarc_v1_generated_eventarc_update_trigger_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py b/owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py deleted file mode 100644 index b6e8d0a4c266..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/scripts/fixup_eventarc_v1_keywords.py +++ /dev/null @@ -1,214 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class eventarcCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_channel': ('parent', 'channel', 'channel_id', 'validate_only', ), - 'create_channel_connection': ('parent', 'channel_connection', 'channel_connection_id', ), - 'create_enrollment': ('parent', 'enrollment', 'enrollment_id', 'validate_only', ), - 'create_google_api_source': ('parent', 'google_api_source', 'google_api_source_id', 'validate_only', ), - 'create_message_bus': ('parent', 'message_bus', 'message_bus_id', 'validate_only', ), - 'create_pipeline': ('parent', 'pipeline', 'pipeline_id', 'validate_only', ), - 'create_trigger': ('parent', 'trigger', 'trigger_id', 'validate_only', ), - 'delete_channel': ('name', 'validate_only', ), - 'delete_channel_connection': ('name', ), - 'delete_enrollment': ('name', 'etag', 'allow_missing', 'validate_only', ), - 'delete_google_api_source': ('name', 'etag', 'allow_missing', 'validate_only', ), - 'delete_message_bus': ('name', 'etag', 'allow_missing', 'validate_only', ), - 'delete_pipeline': ('name', 'etag', 'allow_missing', 'validate_only', ), - 'delete_trigger': ('name', 'etag', 'allow_missing', 'validate_only', ), - 'get_channel': ('name', ), - 'get_channel_connection': ('name', ), - 'get_enrollment': ('name', ), - 'get_google_api_source': ('name', ), - 'get_google_channel_config': ('name', ), - 'get_message_bus': ('name', ), - 'get_pipeline': ('name', ), - 'get_provider': ('name', ), - 'get_trigger': ('name', ), - 'list_channel_connections': ('parent', 'page_size', 'page_token', ), - 'list_channels': ('parent', 'page_size', 'page_token', 'order_by', ), - 'list_enrollments': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'list_google_api_sources': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'list_message_bus_enrollments': ('parent', 'page_size', 'page_token', ), - 'list_message_buses': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'list_pipelines': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'list_providers': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'list_triggers': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'update_channel': ('channel', 'update_mask', 'validate_only', ), - 'update_enrollment': ('enrollment', 'update_mask', 'allow_missing', 'validate_only', ), - 'update_google_api_source': ('google_api_source', 'update_mask', 'allow_missing', 'validate_only', ), - 'update_google_channel_config': ('google_channel_config', 'update_mask', ), - 'update_message_bus': ('message_bus', 'update_mask', 'allow_missing', 'validate_only', ), - 'update_pipeline': ('pipeline', 'update_mask', 'allow_missing', 'validate_only', ), - 'update_trigger': ('trigger', 'update_mask', 'allow_missing', 'validate_only', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=eventarcCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the eventarc client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/setup.py b/owl-bot-staging/google-cloud-eventarc/v1/setup.py deleted file mode 100644 index b54372e5e2d8..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-eventarc' - - -description = "Google Cloud Eventarc API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/eventarc/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py b/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py deleted file mode 100644 index 5254d9ad52a4..000000000000 --- a/owl-bot-staging/google-cloud-eventarc/v1/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ /dev/null @@ -1,32779 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -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 client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.eventarc_v1.services.eventarc import EventarcAsyncClient -from google.cloud.eventarc_v1.services.eventarc import EventarcClient -from google.cloud.eventarc_v1.services.eventarc import pagers -from google.cloud.eventarc_v1.services.eventarc import transports -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel as gce_channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import enrollment as gce_enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import logging_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import message_bus as gce_message_bus -from google.cloud.eventarc_v1.types import network_config -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import pipeline as gce_pipeline -from google.cloud.eventarc_v1.types import trigger -from google.cloud.eventarc_v1.types import trigger as gce_trigger -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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import code_pb2 # type: ignore -import google.auth - - -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 EventarcClient._get_default_mtls_endpoint(None) is None - assert EventarcClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EventarcClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EventarcClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EventarcClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EventarcClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert EventarcClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EventarcClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EventarcClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - EventarcClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert EventarcClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EventarcClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EventarcClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EventarcClient._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 EventarcClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert EventarcClient._get_client_cert_source(None, False) is None - assert EventarcClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EventarcClient._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 EventarcClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EventarcClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) -@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EventarcClient._DEFAULT_UNIVERSE - default_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EventarcClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EventarcClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EventarcClient.DEFAULT_MTLS_ENDPOINT - assert EventarcClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EventarcClient._get_api_endpoint(None, None, default_universe, "always") == EventarcClient.DEFAULT_MTLS_ENDPOINT - assert EventarcClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EventarcClient.DEFAULT_MTLS_ENDPOINT - assert EventarcClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EventarcClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EventarcClient._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 EventarcClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EventarcClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EventarcClient._get_universe_domain(None, None) == EventarcClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EventarcClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EventarcClient, "grpc"), - (EventarcAsyncClient, "grpc_asyncio"), - (EventarcClient, "rest"), -]) -def test_eventarc_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 == ( - 'eventarc.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://eventarc.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EventarcGrpcTransport, "grpc"), - (transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EventarcRestTransport, "rest"), -]) -def test_eventarc_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", [ - (EventarcClient, "grpc"), - (EventarcAsyncClient, "grpc_asyncio"), - (EventarcClient, "rest"), -]) -def test_eventarc_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 == ( - 'eventarc.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://eventarc.googleapis.com' - ) - - -def test_eventarc_client_get_transport_class(): - transport = EventarcClient.get_transport_class() - available_transports = [ - transports.EventarcGrpcTransport, - transports.EventarcRestTransport, - ] - assert transport in available_transports - - transport = EventarcClient.get_transport_class("grpc") - assert transport == transports.EventarcGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EventarcClient, transports.EventarcGrpcTransport, "grpc"), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio"), - (EventarcClient, transports.EventarcRestTransport, "rest"), -]) -@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) -@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) -def test_eventarc_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(EventarcClient, '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(EventarcClient, '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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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", [ - (EventarcClient, transports.EventarcGrpcTransport, "grpc", "true"), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EventarcClient, transports.EventarcGrpcTransport, "grpc", "false"), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EventarcClient, transports.EventarcRestTransport, "rest", "true"), - (EventarcClient, transports.EventarcRestTransport, "rest", "false"), -]) -@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) -@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_eventarc_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", [ - EventarcClient, EventarcAsyncClient -]) -@mock.patch.object(EventarcClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EventarcClient)) -@mock.patch.object(EventarcAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EventarcAsyncClient)) -def test_eventarc_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # 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`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - EventarcClient, EventarcAsyncClient -]) -@mock.patch.object(EventarcClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcClient)) -@mock.patch.object(EventarcAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EventarcAsyncClient)) -def test_eventarc_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EventarcClient._DEFAULT_UNIVERSE - default_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EventarcClient._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", [ - (EventarcClient, transports.EventarcGrpcTransport, "grpc"), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio"), - (EventarcClient, transports.EventarcRestTransport, "rest"), -]) -def test_eventarc_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", [ - (EventarcClient, transports.EventarcGrpcTransport, "grpc", grpc_helpers), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EventarcClient, transports.EventarcRestTransport, "rest", None), -]) -def test_eventarc_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_eventarc_client_client_options_from_dict(): - with mock.patch('google.cloud.eventarc_v1.services.eventarc.transports.EventarcGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EventarcClient( - 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", [ - (EventarcClient, transports.EventarcGrpcTransport, "grpc", grpc_helpers), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_eventarc_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( - "eventarc.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="eventarc.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetTriggerRequest, - dict, -]) -def test_get_trigger(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trigger.Trigger( - name='name_value', - uid='uid_value', - service_account='service_account_value', - channel='channel_value', - event_data_content_type='event_data_content_type_value', - satisfies_pzs=True, - etag='etag_value', - ) - response = client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetTriggerRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trigger.Trigger) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.service_account == 'service_account_value' - assert response.channel == 'channel_value' - assert response.event_data_content_type == 'event_data_content_type_value' - assert response.satisfies_pzs is True - assert response.etag == 'etag_value' - - -def test_get_trigger_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 = EventarcClient( - 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 = eventarc.GetTriggerRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_trigger(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetTriggerRequest( - name='name_value', - ) - -def test_get_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - request = {} - client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_trigger(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_trigger_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 = EventarcAsyncClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - await client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetTriggerRequest): - client = EventarcAsyncClient( - 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_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger( - name='name_value', - uid='uid_value', - service_account='service_account_value', - channel='channel_value', - event_data_content_type='event_data_content_type_value', - satisfies_pzs=True, - etag='etag_value', - )) - response = await client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetTriggerRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trigger.Trigger) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.service_account == 'service_account_value' - assert response.channel == 'channel_value' - assert response.event_data_content_type == 'event_data_content_type_value' - assert response.satisfies_pzs is True - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_trigger_async_from_dict(): - await test_get_trigger_async(request_type=dict) - -def test_get_trigger_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetTriggerRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - call.return_value = trigger.Trigger() - client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_trigger_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetTriggerRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger()) - await client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_trigger_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trigger.Trigger() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_trigger( - name='name_value', - ) - - # 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_trigger_flattened_error(): - client = EventarcClient( - credentials=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_trigger( - eventarc.GetTriggerRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_trigger_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trigger.Trigger() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_trigger( - name='name_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_trigger_flattened_error_async(): - client = EventarcAsyncClient( - 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_trigger( - eventarc.GetTriggerRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListTriggersRequest, - dict, -]) -def test_list_triggers(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListTriggersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListTriggersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTriggersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_triggers_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 = EventarcClient( - 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 = eventarc.ListTriggersRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_triggers(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListTriggersRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - -def test_list_triggers_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 = EventarcClient( - 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_triggers 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_triggers] = mock_rpc - request = {} - client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_triggers(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_triggers_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 = EventarcAsyncClient( - 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_triggers 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_triggers] = mock_rpc - - request = {} - await client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_triggers(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_triggers_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListTriggersRequest): - client = EventarcAsyncClient( - 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_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListTriggersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTriggersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_triggers_async_from_dict(): - await test_list_triggers_async(request_type=dict) - -def test_list_triggers_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListTriggersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - call.return_value = eventarc.ListTriggersResponse() - client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_triggers_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListTriggersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse()) - await client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_triggers_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListTriggersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_triggers( - 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_triggers_flattened_error(): - client = EventarcClient( - credentials=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_triggers( - eventarc.ListTriggersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_triggers_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListTriggersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_triggers( - 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_triggers_flattened_error_async(): - client = EventarcAsyncClient( - 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_triggers( - eventarc.ListTriggersRequest(), - parent='parent_value', - ) - - -def test_list_triggers_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_triggers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - trigger.Trigger(), - ], - next_page_token='abc', - ), - eventarc.ListTriggersResponse( - triggers=[], - next_page_token='def', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - ], - next_page_token='ghi', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_triggers(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, trigger.Trigger) - for i in results) -def test_list_triggers_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_triggers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - trigger.Trigger(), - ], - next_page_token='abc', - ), - eventarc.ListTriggersResponse( - triggers=[], - next_page_token='def', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - ], - next_page_token='ghi', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - ], - ), - RuntimeError, - ) - pages = list(client.list_triggers(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_triggers_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - trigger.Trigger(), - ], - next_page_token='abc', - ), - eventarc.ListTriggersResponse( - triggers=[], - next_page_token='def', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - ], - next_page_token='ghi', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_triggers(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, trigger.Trigger) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_triggers_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - trigger.Trigger(), - ], - next_page_token='abc', - ), - eventarc.ListTriggersResponse( - triggers=[], - next_page_token='def', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - ], - next_page_token='ghi', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - ], - ), - 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_triggers(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", [ - eventarc.CreateTriggerRequest, - dict, -]) -def test_create_trigger(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreateTriggerRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_trigger_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 = EventarcClient( - 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 = eventarc.CreateTriggerRequest( - parent='parent_value', - trigger_id='trigger_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_trigger(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreateTriggerRequest( - parent='parent_value', - trigger_id='trigger_id_value', - ) - -def test_create_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - request = {} - client.create_trigger(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_trigger(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_trigger_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 = EventarcAsyncClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - await client.create_trigger(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_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateTriggerRequest): - client = EventarcAsyncClient( - 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_trigger), - '__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_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreateTriggerRequest() - 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_trigger_async_from_dict(): - await test_create_trigger_async(request_type=dict) - -def test_create_trigger_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreateTriggerRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_trigger_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreateTriggerRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_trigger_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__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_trigger( - parent='parent_value', - trigger=gce_trigger.Trigger(name='name_value'), - trigger_id='trigger_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].trigger - mock_val = gce_trigger.Trigger(name='name_value') - assert arg == mock_val - arg = args[0].trigger_id - mock_val = 'trigger_id_value' - assert arg == mock_val - - -def test_create_trigger_flattened_error(): - client = EventarcClient( - credentials=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_trigger( - eventarc.CreateTriggerRequest(), - parent='parent_value', - trigger=gce_trigger.Trigger(name='name_value'), - trigger_id='trigger_id_value', - ) - -@pytest.mark.asyncio -async def test_create_trigger_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__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_trigger( - parent='parent_value', - trigger=gce_trigger.Trigger(name='name_value'), - trigger_id='trigger_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].trigger - mock_val = gce_trigger.Trigger(name='name_value') - assert arg == mock_val - arg = args[0].trigger_id - mock_val = 'trigger_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_trigger_flattened_error_async(): - client = EventarcAsyncClient( - 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_trigger( - eventarc.CreateTriggerRequest(), - parent='parent_value', - trigger=gce_trigger.Trigger(name='name_value'), - trigger_id='trigger_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateTriggerRequest, - dict, -]) -def test_update_trigger(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateTriggerRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_trigger_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 = EventarcClient( - 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 = eventarc.UpdateTriggerRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_trigger(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdateTriggerRequest( - ) - -def test_update_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - request = {} - client.update_trigger(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.update_trigger(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_trigger_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 = EventarcAsyncClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - await client.update_trigger(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.update_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateTriggerRequest): - client = EventarcAsyncClient( - 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_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateTriggerRequest() - 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_update_trigger_async_from_dict(): - await test_update_trigger_async(request_type=dict) - -def test_update_trigger_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdateTriggerRequest() - - request.trigger.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'trigger.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_trigger_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdateTriggerRequest() - - request.trigger.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'trigger.name=name_value', - ) in kw['metadata'] - - -def test_update_trigger_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_trigger( - trigger=gce_trigger.Trigger(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - allow_missing=True, - ) - - # 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].trigger - mock_val = gce_trigger.Trigger(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].allow_missing - mock_val = True - assert arg == mock_val - - -def test_update_trigger_flattened_error(): - client = EventarcClient( - credentials=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_trigger( - eventarc.UpdateTriggerRequest(), - trigger=gce_trigger.Trigger(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - allow_missing=True, - ) - -@pytest.mark.asyncio -async def test_update_trigger_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_trigger( - trigger=gce_trigger.Trigger(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - allow_missing=True, - ) - - # 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].trigger - mock_val = gce_trigger.Trigger(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].allow_missing - mock_val = True - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_trigger_flattened_error_async(): - client = EventarcAsyncClient( - 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_trigger( - eventarc.UpdateTriggerRequest(), - trigger=gce_trigger.Trigger(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - allow_missing=True, - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteTriggerRequest, - dict, -]) -def test_delete_trigger(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteTriggerRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_trigger_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 = EventarcClient( - 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 = eventarc.DeleteTriggerRequest( - 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_trigger), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_trigger(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeleteTriggerRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - request = {} - client.delete_trigger(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_trigger(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_trigger_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 = EventarcAsyncClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - await client.delete_trigger(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_trigger(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_trigger_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteTriggerRequest): - client = EventarcAsyncClient( - 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_trigger), - '__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_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteTriggerRequest() - 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_trigger_async_from_dict(): - await test_delete_trigger_async(request_type=dict) - -def test_delete_trigger_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeleteTriggerRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_trigger_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeleteTriggerRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_trigger_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__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_trigger( - name='name_value', - allow_missing=True, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].allow_missing - mock_val = True - assert arg == mock_val - - -def test_delete_trigger_flattened_error(): - client = EventarcClient( - credentials=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_trigger( - eventarc.DeleteTriggerRequest(), - name='name_value', - allow_missing=True, - ) - -@pytest.mark.asyncio -async def test_delete_trigger_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__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_trigger( - name='name_value', - allow_missing=True, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].allow_missing - mock_val = True - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_trigger_flattened_error_async(): - client = EventarcAsyncClient( - 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_trigger( - eventarc.DeleteTriggerRequest(), - name='name_value', - allow_missing=True, - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetChannelRequest, - dict, -]) -def test_get_channel(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = channel.Channel( - name='name_value', - uid='uid_value', - provider='provider_value', - state=channel.Channel.State.PENDING, - activation_token='activation_token_value', - crypto_key_name='crypto_key_name_value', - satisfies_pzs=True, - pubsub_topic='pubsub_topic_value', - ) - response = client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetChannelRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, channel.Channel) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.provider == 'provider_value' - assert response.state == channel.Channel.State.PENDING - assert response.activation_token == 'activation_token_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.satisfies_pzs is True - - -def test_get_channel_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 = EventarcClient( - 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 = eventarc.GetChannelRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_channel(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetChannelRequest( - name='name_value', - ) - -def test_get_channel_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 = EventarcClient( - 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_channel 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_channel] = mock_rpc - request = {} - client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_channel(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_channel_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 = EventarcAsyncClient( - 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_channel 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_channel] = mock_rpc - - request = {} - await client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetChannelRequest): - client = EventarcAsyncClient( - 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_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel( - name='name_value', - uid='uid_value', - provider='provider_value', - state=channel.Channel.State.PENDING, - activation_token='activation_token_value', - crypto_key_name='crypto_key_name_value', - satisfies_pzs=True, - )) - response = await client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetChannelRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, channel.Channel) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.provider == 'provider_value' - assert response.state == channel.Channel.State.PENDING - assert response.activation_token == 'activation_token_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.satisfies_pzs is True - - -@pytest.mark.asyncio -async def test_get_channel_async_from_dict(): - await test_get_channel_async(request_type=dict) - -def test_get_channel_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetChannelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - call.return_value = channel.Channel() - client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetChannelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel()) - await client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = channel.Channel() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_channel( - name='name_value', - ) - - # 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_channel_flattened_error(): - client = EventarcClient( - credentials=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_channel( - eventarc.GetChannelRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_channel_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = channel.Channel() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_channel( - name='name_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_channel_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel( - eventarc.GetChannelRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListChannelsRequest, - dict, -]) -def test_list_channels(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListChannelsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListChannelsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_channels_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 = EventarcClient( - 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 = eventarc.ListChannelsRequest( - parent='parent_value', - page_token='page_token_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_channels), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_channels(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListChannelsRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - ) - -def test_list_channels_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 = EventarcClient( - 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_channels 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_channels] = mock_rpc - request = {} - client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_channels(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_channels_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 = EventarcAsyncClient( - 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_channels 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_channels] = mock_rpc - - request = {} - await client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_channels(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_channels_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListChannelsRequest): - client = EventarcAsyncClient( - 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_channels), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListChannelsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_channels_async_from_dict(): - await test_list_channels_async(request_type=dict) - -def test_list_channels_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListChannelsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - call.return_value = eventarc.ListChannelsResponse() - client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channels_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListChannelsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse()) - await client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channels_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListChannelsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_channels( - 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_channels_flattened_error(): - client = EventarcClient( - credentials=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_channels( - eventarc.ListChannelsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_channels_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListChannelsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_channels( - 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_channels_flattened_error_async(): - client = EventarcAsyncClient( - 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_channels( - eventarc.ListChannelsRequest(), - parent='parent_value', - ) - - -def test_list_channels_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_channels), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - channel.Channel(), - ], - next_page_token='abc', - ), - eventarc.ListChannelsResponse( - channels=[], - next_page_token='def', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_channels(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, channel.Channel) - for i in results) -def test_list_channels_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_channels), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - channel.Channel(), - ], - next_page_token='abc', - ), - eventarc.ListChannelsResponse( - channels=[], - next_page_token='def', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - ], - ), - RuntimeError, - ) - pages = list(client.list_channels(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_channels_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - channel.Channel(), - ], - next_page_token='abc', - ), - eventarc.ListChannelsResponse( - channels=[], - next_page_token='def', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_channels(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, channel.Channel) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_channels_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - channel.Channel(), - ], - next_page_token='abc', - ), - eventarc.ListChannelsResponse( - channels=[], - next_page_token='def', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - ], - ), - 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_channels(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", [ - eventarc.CreateChannelRequest, - dict, -]) -def test_create_channel(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreateChannelRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_channel_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 = EventarcClient( - 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 = eventarc.CreateChannelRequest( - parent='parent_value', - channel_id='channel_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_channel(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreateChannelRequest( - parent='parent_value', - channel_id='channel_id_value', - ) - -def test_create_channel_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 = EventarcClient( - 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_channel_ 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_channel_] = mock_rpc - request = {} - client.create_channel(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_channel(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_channel_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 = EventarcAsyncClient( - 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_channel_ 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_channel_] = mock_rpc - - request = {} - await client.create_channel(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_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateChannelRequest): - client = EventarcAsyncClient( - 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_channel_), - '__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_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreateChannelRequest() - 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_channel_async_from_dict(): - await test_create_channel_async(request_type=dict) - -def test_create_channel_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreateChannelRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreateChannelRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__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_channel( - parent='parent_value', - channel=gce_channel.Channel(name='name_value'), - channel_id='channel_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].channel - mock_val = gce_channel.Channel(name='name_value') - assert arg == mock_val - arg = args[0].channel_id - mock_val = 'channel_id_value' - assert arg == mock_val - - -def test_create_channel_flattened_error(): - client = EventarcClient( - credentials=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_channel( - eventarc.CreateChannelRequest(), - parent='parent_value', - channel=gce_channel.Channel(name='name_value'), - channel_id='channel_id_value', - ) - -@pytest.mark.asyncio -async def test_create_channel_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__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_channel( - parent='parent_value', - channel=gce_channel.Channel(name='name_value'), - channel_id='channel_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].channel - mock_val = gce_channel.Channel(name='name_value') - assert arg == mock_val - arg = args[0].channel_id - mock_val = 'channel_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_channel_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel( - eventarc.CreateChannelRequest(), - parent='parent_value', - channel=gce_channel.Channel(name='name_value'), - channel_id='channel_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateChannelRequest, - dict, -]) -def test_update_channel(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateChannelRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_channel_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 = EventarcClient( - 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 = eventarc.UpdateChannelRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_channel(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdateChannelRequest( - ) - -def test_update_channel_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 = EventarcClient( - 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_channel 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_channel] = mock_rpc - request = {} - client.update_channel(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.update_channel(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_channel_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 = EventarcAsyncClient( - 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_channel 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_channel] = mock_rpc - - request = {} - await client.update_channel(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.update_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateChannelRequest): - client = EventarcAsyncClient( - 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_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateChannelRequest() - 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_update_channel_async_from_dict(): - await test_update_channel_async(request_type=dict) - -def test_update_channel_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdateChannelRequest() - - request.channel.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'channel.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_channel_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdateChannelRequest() - - request.channel.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'channel.name=name_value', - ) in kw['metadata'] - - -def test_update_channel_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_channel( - channel=gce_channel.Channel(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].channel - mock_val = gce_channel.Channel(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_channel_flattened_error(): - client = EventarcClient( - credentials=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_channel( - eventarc.UpdateChannelRequest(), - channel=gce_channel.Channel(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_channel_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_channel( - channel=gce_channel.Channel(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].channel - mock_val = gce_channel.Channel(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_channel_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel( - eventarc.UpdateChannelRequest(), - channel=gce_channel.Channel(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteChannelRequest, - dict, -]) -def test_delete_channel(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteChannelRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_channel_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 = EventarcClient( - 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 = eventarc.DeleteChannelRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_channel(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeleteChannelRequest( - name='name_value', - ) - -def test_delete_channel_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 = EventarcClient( - 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_channel 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_channel] = mock_rpc - request = {} - client.delete_channel(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_channel(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_channel_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 = EventarcAsyncClient( - 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_channel 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_channel] = mock_rpc - - request = {} - await client.delete_channel(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_channel(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_channel_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteChannelRequest): - client = EventarcAsyncClient( - 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_channel), - '__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_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteChannelRequest() - 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_channel_async_from_dict(): - await test_delete_channel_async(request_type=dict) - -def test_delete_channel_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeleteChannelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeleteChannelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__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_channel( - name='name_value', - ) - - # 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_channel_flattened_error(): - client = EventarcClient( - credentials=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_channel( - eventarc.DeleteChannelRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_channel_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__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_channel( - name='name_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_channel_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel( - eventarc.DeleteChannelRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetProviderRequest, - dict, -]) -def test_get_provider(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = discovery.Provider( - name='name_value', - display_name='display_name_value', - ) - response = client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetProviderRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, discovery.Provider) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_provider_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 = EventarcClient( - 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 = eventarc.GetProviderRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_provider(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetProviderRequest( - name='name_value', - ) - -def test_get_provider_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 = EventarcClient( - 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_provider 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_provider] = mock_rpc - request = {} - client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_provider(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_provider_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 = EventarcAsyncClient( - 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_provider 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_provider] = mock_rpc - - request = {} - await client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_provider(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_provider_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetProviderRequest): - client = EventarcAsyncClient( - 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_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider( - name='name_value', - display_name='display_name_value', - )) - response = await client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetProviderRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, discovery.Provider) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_provider_async_from_dict(): - await test_get_provider_async(request_type=dict) - -def test_get_provider_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetProviderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - call.return_value = discovery.Provider() - client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_provider_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetProviderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider()) - await client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_provider_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = discovery.Provider() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_provider( - name='name_value', - ) - - # 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_provider_flattened_error(): - client = EventarcClient( - credentials=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_provider( - eventarc.GetProviderRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_provider_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = discovery.Provider() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_provider( - name='name_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_provider_flattened_error_async(): - client = EventarcAsyncClient( - 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_provider( - eventarc.GetProviderRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListProvidersRequest, - dict, -]) -def test_list_providers(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListProvidersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListProvidersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProvidersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_providers_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 = EventarcClient( - 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 = eventarc.ListProvidersRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_providers(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListProvidersRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - -def test_list_providers_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 = EventarcClient( - 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_providers 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_providers] = mock_rpc - request = {} - client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_providers(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_providers_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 = EventarcAsyncClient( - 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_providers 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_providers] = mock_rpc - - request = {} - await client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_providers(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_providers_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListProvidersRequest): - client = EventarcAsyncClient( - 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_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListProvidersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProvidersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_providers_async_from_dict(): - await test_list_providers_async(request_type=dict) - -def test_list_providers_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListProvidersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - call.return_value = eventarc.ListProvidersResponse() - client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_providers_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListProvidersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse()) - await client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_providers_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListProvidersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_providers( - 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_providers_flattened_error(): - client = EventarcClient( - credentials=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_providers( - eventarc.ListProvidersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_providers_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListProvidersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_providers( - 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_providers_flattened_error_async(): - client = EventarcAsyncClient( - 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_providers( - eventarc.ListProvidersRequest(), - parent='parent_value', - ) - - -def test_list_providers_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_providers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - discovery.Provider(), - ], - next_page_token='abc', - ), - eventarc.ListProvidersResponse( - providers=[], - next_page_token='def', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - ], - next_page_token='ghi', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_providers(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, discovery.Provider) - for i in results) -def test_list_providers_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_providers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - discovery.Provider(), - ], - next_page_token='abc', - ), - eventarc.ListProvidersResponse( - providers=[], - next_page_token='def', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - ], - next_page_token='ghi', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - ], - ), - RuntimeError, - ) - pages = list(client.list_providers(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_providers_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - discovery.Provider(), - ], - next_page_token='abc', - ), - eventarc.ListProvidersResponse( - providers=[], - next_page_token='def', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - ], - next_page_token='ghi', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_providers(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, discovery.Provider) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_providers_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - discovery.Provider(), - ], - next_page_token='abc', - ), - eventarc.ListProvidersResponse( - providers=[], - next_page_token='def', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - ], - next_page_token='ghi', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - ], - ), - 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_providers(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", [ - eventarc.GetChannelConnectionRequest, - dict, -]) -def test_get_channel_connection(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = channel_connection.ChannelConnection( - name='name_value', - uid='uid_value', - channel='channel_value', - activation_token='activation_token_value', - ) - response = client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetChannelConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, channel_connection.ChannelConnection) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.channel == 'channel_value' - assert response.activation_token == 'activation_token_value' - - -def test_get_channel_connection_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 = EventarcClient( - 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 = eventarc.GetChannelConnectionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_channel_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetChannelConnectionRequest( - name='name_value', - ) - -def test_get_channel_connection_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 = EventarcClient( - 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_channel_connection 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_channel_connection] = mock_rpc - request = {} - client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_channel_connection(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_channel_connection_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 = EventarcAsyncClient( - 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_channel_connection 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_channel_connection] = mock_rpc - - request = {} - await client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_channel_connection(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_channel_connection_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetChannelConnectionRequest): - client = EventarcAsyncClient( - 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_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection( - name='name_value', - uid='uid_value', - channel='channel_value', - activation_token='activation_token_value', - )) - response = await client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetChannelConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, channel_connection.ChannelConnection) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.channel == 'channel_value' - assert response.activation_token == 'activation_token_value' - - -@pytest.mark.asyncio -async def test_get_channel_connection_async_from_dict(): - await test_get_channel_connection_async(request_type=dict) - -def test_get_channel_connection_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetChannelConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - call.return_value = channel_connection.ChannelConnection() - client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_connection_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetChannelConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection()) - await client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_connection_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = channel_connection.ChannelConnection() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_channel_connection( - name='name_value', - ) - - # 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_channel_connection_flattened_error(): - client = EventarcClient( - credentials=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_channel_connection( - eventarc.GetChannelConnectionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_channel_connection_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = channel_connection.ChannelConnection() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_channel_connection( - name='name_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_channel_connection_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel_connection( - eventarc.GetChannelConnectionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListChannelConnectionsRequest, - dict, -]) -def test_list_channel_connections(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListChannelConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListChannelConnectionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelConnectionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_channel_connections_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 = EventarcClient( - 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 = eventarc.ListChannelConnectionsRequest( - 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_channel_connections), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_channel_connections(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListChannelConnectionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_channel_connections_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 = EventarcClient( - 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_channel_connections 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_channel_connections] = mock_rpc - request = {} - client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_channel_connections(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_channel_connections_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 = EventarcAsyncClient( - 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_channel_connections 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_channel_connections] = mock_rpc - - request = {} - await client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_channel_connections(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_channel_connections_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListChannelConnectionsRequest): - client = EventarcAsyncClient( - 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_channel_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListChannelConnectionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelConnectionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_channel_connections_async_from_dict(): - await test_list_channel_connections_async(request_type=dict) - -def test_list_channel_connections_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListChannelConnectionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - call.return_value = eventarc.ListChannelConnectionsResponse() - client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_connections_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListChannelConnectionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse()) - await client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_connections_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListChannelConnectionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_channel_connections( - 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_channel_connections_flattened_error(): - client = EventarcClient( - credentials=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_channel_connections( - eventarc.ListChannelConnectionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_channel_connections_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListChannelConnectionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_channel_connections( - 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_channel_connections_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel_connections( - eventarc.ListChannelConnectionsRequest(), - parent='parent_value', - ) - - -def test_list_channel_connections_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_channel_connections), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - next_page_token='abc', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[], - next_page_token='def', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_channel_connections(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, channel_connection.ChannelConnection) - for i in results) -def test_list_channel_connections_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_channel_connections), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - next_page_token='abc', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[], - next_page_token='def', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - ), - RuntimeError, - ) - pages = list(client.list_channel_connections(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_channel_connections_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - next_page_token='abc', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[], - next_page_token='def', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_channel_connections(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, channel_connection.ChannelConnection) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_channel_connections_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - next_page_token='abc', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[], - next_page_token='def', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - ), - 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_channel_connections(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", [ - eventarc.CreateChannelConnectionRequest, - dict, -]) -def test_create_channel_connection(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreateChannelConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_channel_connection_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 = EventarcClient( - 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 = eventarc.CreateChannelConnectionRequest( - parent='parent_value', - channel_connection_id='channel_connection_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_channel_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreateChannelConnectionRequest( - parent='parent_value', - channel_connection_id='channel_connection_id_value', - ) - -def test_create_channel_connection_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 = EventarcClient( - 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_channel_connection 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_channel_connection] = mock_rpc - request = {} - client.create_channel_connection(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_channel_connection(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_channel_connection_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 = EventarcAsyncClient( - 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_channel_connection 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_channel_connection] = mock_rpc - - request = {} - await client.create_channel_connection(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_channel_connection(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_channel_connection_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateChannelConnectionRequest): - client = EventarcAsyncClient( - 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_channel_connection), - '__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_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreateChannelConnectionRequest() - 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_channel_connection_async_from_dict(): - await test_create_channel_connection_async(request_type=dict) - -def test_create_channel_connection_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreateChannelConnectionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_connection_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreateChannelConnectionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_connection_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__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_channel_connection( - parent='parent_value', - channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), - channel_connection_id='channel_connection_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].channel_connection - mock_val = gce_channel_connection.ChannelConnection(name='name_value') - assert arg == mock_val - arg = args[0].channel_connection_id - mock_val = 'channel_connection_id_value' - assert arg == mock_val - - -def test_create_channel_connection_flattened_error(): - client = EventarcClient( - credentials=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_channel_connection( - eventarc.CreateChannelConnectionRequest(), - parent='parent_value', - channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), - channel_connection_id='channel_connection_id_value', - ) - -@pytest.mark.asyncio -async def test_create_channel_connection_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__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_channel_connection( - parent='parent_value', - channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), - channel_connection_id='channel_connection_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].channel_connection - mock_val = gce_channel_connection.ChannelConnection(name='name_value') - assert arg == mock_val - arg = args[0].channel_connection_id - mock_val = 'channel_connection_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_channel_connection_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel_connection( - eventarc.CreateChannelConnectionRequest(), - parent='parent_value', - channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), - channel_connection_id='channel_connection_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteChannelConnectionRequest, - dict, -]) -def test_delete_channel_connection(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteChannelConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_channel_connection_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 = EventarcClient( - 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 = eventarc.DeleteChannelConnectionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_channel_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeleteChannelConnectionRequest( - name='name_value', - ) - -def test_delete_channel_connection_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 = EventarcClient( - 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_channel_connection 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_channel_connection] = mock_rpc - request = {} - client.delete_channel_connection(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_channel_connection(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_channel_connection_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 = EventarcAsyncClient( - 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_channel_connection 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_channel_connection] = mock_rpc - - request = {} - await client.delete_channel_connection(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_channel_connection(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_channel_connection_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteChannelConnectionRequest): - client = EventarcAsyncClient( - 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_channel_connection), - '__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_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteChannelConnectionRequest() - 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_channel_connection_async_from_dict(): - await test_delete_channel_connection_async(request_type=dict) - -def test_delete_channel_connection_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeleteChannelConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_channel_connection_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeleteChannelConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_channel_connection_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__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_channel_connection( - name='name_value', - ) - - # 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_channel_connection_flattened_error(): - client = EventarcClient( - credentials=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_channel_connection( - eventarc.DeleteChannelConnectionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_channel_connection_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__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_channel_connection( - name='name_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_channel_connection_flattened_error_async(): - client = EventarcAsyncClient( - 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_channel_connection( - eventarc.DeleteChannelConnectionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetGoogleChannelConfigRequest, - dict, -]) -def test_get_google_channel_config(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_name_value', - ) - response = client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetGoogleChannelConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, google_channel_config.GoogleChannelConfig) - assert response.name == 'name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -def test_get_google_channel_config_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 = EventarcClient( - 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 = eventarc.GetGoogleChannelConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_google_channel_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetGoogleChannelConfigRequest( - name='name_value', - ) - -def test_get_google_channel_config_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 = EventarcClient( - 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_google_channel_config 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_google_channel_config] = mock_rpc - request = {} - client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_google_channel_config(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_google_channel_config_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 = EventarcAsyncClient( - 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_google_channel_config 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_google_channel_config] = mock_rpc - - request = {} - await client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_google_channel_config(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_google_channel_config_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetGoogleChannelConfigRequest): - client = EventarcAsyncClient( - 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_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_name_value', - )) - response = await client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetGoogleChannelConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, google_channel_config.GoogleChannelConfig) - assert response.name == 'name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.asyncio -async def test_get_google_channel_config_async_from_dict(): - await test_get_google_channel_config_async(request_type=dict) - -def test_get_google_channel_config_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetGoogleChannelConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - call.return_value = google_channel_config.GoogleChannelConfig() - client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_google_channel_config_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetGoogleChannelConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig()) - await client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_google_channel_config_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = google_channel_config.GoogleChannelConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_google_channel_config( - name='name_value', - ) - - # 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_google_channel_config_flattened_error(): - client = EventarcClient( - credentials=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_google_channel_config( - eventarc.GetGoogleChannelConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_google_channel_config_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = google_channel_config.GoogleChannelConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_google_channel_config( - name='name_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_google_channel_config_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_channel_config( - eventarc.GetGoogleChannelConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateGoogleChannelConfigRequest, - dict, -]) -def test_update_google_channel_config(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gce_google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_name_value', - ) - response = client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateGoogleChannelConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) - assert response.name == 'name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -def test_update_google_channel_config_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 = EventarcClient( - 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 = eventarc.UpdateGoogleChannelConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_google_channel_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdateGoogleChannelConfigRequest( - ) - -def test_update_google_channel_config_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 = EventarcClient( - 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_google_channel_config 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_google_channel_config] = mock_rpc - request = {} - client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_google_channel_config(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_google_channel_config_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 = EventarcAsyncClient( - 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_google_channel_config 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_google_channel_config] = mock_rpc - - request = {} - await client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_google_channel_config(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_google_channel_config_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateGoogleChannelConfigRequest): - client = EventarcAsyncClient( - 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_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_name_value', - )) - response = await client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateGoogleChannelConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) - assert response.name == 'name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.asyncio -async def test_update_google_channel_config_async_from_dict(): - await test_update_google_channel_config_async(request_type=dict) - -def test_update_google_channel_config_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdateGoogleChannelConfigRequest() - - request.google_channel_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - call.return_value = gce_google_channel_config.GoogleChannelConfig() - client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'google_channel_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_google_channel_config_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdateGoogleChannelConfigRequest() - - request.google_channel_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig()) - await client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'google_channel_config.name=name_value', - ) in kw['metadata'] - - -def test_update_google_channel_config_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gce_google_channel_config.GoogleChannelConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_google_channel_config( - google_channel_config=gce_google_channel_config.GoogleChannelConfig(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].google_channel_config - mock_val = gce_google_channel_config.GoogleChannelConfig(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_google_channel_config_flattened_error(): - client = EventarcClient( - credentials=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_google_channel_config( - eventarc.UpdateGoogleChannelConfigRequest(), - google_channel_config=gce_google_channel_config.GoogleChannelConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_google_channel_config_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gce_google_channel_config.GoogleChannelConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_google_channel_config( - google_channel_config=gce_google_channel_config.GoogleChannelConfig(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].google_channel_config - mock_val = gce_google_channel_config.GoogleChannelConfig(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_google_channel_config_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_channel_config( - eventarc.UpdateGoogleChannelConfigRequest(), - google_channel_config=gce_google_channel_config.GoogleChannelConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetMessageBusRequest, - dict, -]) -def test_get_message_bus(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = message_bus.MessageBus( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - ) - response = client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetMessageBusRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, message_bus.MessageBus) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -def test_get_message_bus_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 = EventarcClient( - 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 = eventarc.GetMessageBusRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_message_bus(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetMessageBusRequest( - name='name_value', - ) - -def test_get_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - request = {} - client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_message_bus(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_message_bus_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 = EventarcAsyncClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - await client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetMessageBusRequest): - client = EventarcAsyncClient( - 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_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - )) - response = await client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetMessageBusRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, message_bus.MessageBus) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.asyncio -async def test_get_message_bus_async_from_dict(): - await test_get_message_bus_async(request_type=dict) - -def test_get_message_bus_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetMessageBusRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - call.return_value = message_bus.MessageBus() - client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_message_bus_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetMessageBusRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus()) - await client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_message_bus_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = message_bus.MessageBus() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_message_bus( - name='name_value', - ) - - # 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_message_bus_flattened_error(): - client = EventarcClient( - credentials=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_message_bus( - eventarc.GetMessageBusRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_message_bus_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = message_bus.MessageBus() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_message_bus( - name='name_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_message_bus_flattened_error_async(): - client = EventarcAsyncClient( - 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_message_bus( - eventarc.GetMessageBusRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListMessageBusesRequest, - dict, -]) -def test_list_message_buses(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListMessageBusesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListMessageBusesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessageBusesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_message_buses_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 = EventarcClient( - 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 = eventarc.ListMessageBusesRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_message_buses(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListMessageBusesRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - -def test_list_message_buses_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 = EventarcClient( - 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_message_buses 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_message_buses] = mock_rpc - request = {} - client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_message_buses(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_message_buses_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 = EventarcAsyncClient( - 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_message_buses 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_message_buses] = mock_rpc - - request = {} - await client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_message_buses(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_message_buses_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListMessageBusesRequest): - client = EventarcAsyncClient( - 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_message_buses), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListMessageBusesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessageBusesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_message_buses_async_from_dict(): - await test_list_message_buses_async(request_type=dict) - -def test_list_message_buses_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListMessageBusesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - call.return_value = eventarc.ListMessageBusesResponse() - client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_message_buses_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListMessageBusesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse()) - await client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_message_buses_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListMessageBusesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_message_buses( - 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_message_buses_flattened_error(): - client = EventarcClient( - credentials=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_message_buses( - eventarc.ListMessageBusesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_message_buses_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListMessageBusesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_message_buses( - 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_message_buses_flattened_error_async(): - client = EventarcAsyncClient( - 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_message_buses( - eventarc.ListMessageBusesRequest(), - parent='parent_value', - ) - - -def test_list_message_buses_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_message_buses), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusesResponse( - message_buses=[], - next_page_token='def', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_message_buses(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, message_bus.MessageBus) - for i in results) -def test_list_message_buses_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_message_buses), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusesResponse( - message_buses=[], - next_page_token='def', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - ), - RuntimeError, - ) - pages = list(client.list_message_buses(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_message_buses_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusesResponse( - message_buses=[], - next_page_token='def', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_message_buses(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, message_bus.MessageBus) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_message_buses_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusesResponse( - message_buses=[], - next_page_token='def', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - ), - 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_message_buses(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", [ - eventarc.ListMessageBusEnrollmentsRequest, - dict, -]) -def test_list_message_bus_enrollments(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListMessageBusEnrollmentsResponse( - enrollments=['enrollments_value'], - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListMessageBusEnrollmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessageBusEnrollmentsPager) - assert response.enrollments == ['enrollments_value'] - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_message_bus_enrollments_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 = EventarcClient( - 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 = eventarc.ListMessageBusEnrollmentsRequest( - 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_message_bus_enrollments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_message_bus_enrollments(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListMessageBusEnrollmentsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_message_bus_enrollments_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 = EventarcClient( - 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_message_bus_enrollments 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_message_bus_enrollments] = mock_rpc - request = {} - client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_message_bus_enrollments(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_message_bus_enrollments_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 = EventarcAsyncClient( - 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_message_bus_enrollments 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_message_bus_enrollments] = mock_rpc - - request = {} - await client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_message_bus_enrollments(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_message_bus_enrollments_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListMessageBusEnrollmentsRequest): - client = EventarcAsyncClient( - 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_message_bus_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse( - enrollments=['enrollments_value'], - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListMessageBusEnrollmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessageBusEnrollmentsAsyncPager) - assert response.enrollments == ['enrollments_value'] - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_message_bus_enrollments_async_from_dict(): - await test_list_message_bus_enrollments_async(request_type=dict) - -def test_list_message_bus_enrollments_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListMessageBusEnrollmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - call.return_value = eventarc.ListMessageBusEnrollmentsResponse() - client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_message_bus_enrollments_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListMessageBusEnrollmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse()) - await client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_message_bus_enrollments_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListMessageBusEnrollmentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_message_bus_enrollments( - 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_message_bus_enrollments_flattened_error(): - client = EventarcClient( - credentials=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_message_bus_enrollments( - eventarc.ListMessageBusEnrollmentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_message_bus_enrollments_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListMessageBusEnrollmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_message_bus_enrollments( - 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_message_bus_enrollments_flattened_error_async(): - client = EventarcAsyncClient( - 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_message_bus_enrollments( - eventarc.ListMessageBusEnrollmentsRequest(), - parent='parent_value', - ) - - -def test_list_message_bus_enrollments_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_message_bus_enrollments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_message_bus_enrollments(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, str) - for i in results) -def test_list_message_bus_enrollments_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_message_bus_enrollments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = list(client.list_message_bus_enrollments(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_message_bus_enrollments_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_message_bus_enrollments(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, str) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_message_bus_enrollments_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - ], - ), - 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_message_bus_enrollments(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", [ - eventarc.CreateMessageBusRequest, - dict, -]) -def test_create_message_bus(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreateMessageBusRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_message_bus_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 = EventarcClient( - 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 = eventarc.CreateMessageBusRequest( - parent='parent_value', - message_bus_id='message_bus_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_message_bus(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreateMessageBusRequest( - parent='parent_value', - message_bus_id='message_bus_id_value', - ) - -def test_create_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - request = {} - client.create_message_bus(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_message_bus(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_message_bus_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 = EventarcAsyncClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - await client.create_message_bus(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_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateMessageBusRequest): - client = EventarcAsyncClient( - 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_message_bus), - '__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_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreateMessageBusRequest() - 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_message_bus_async_from_dict(): - await test_create_message_bus_async(request_type=dict) - -def test_create_message_bus_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreateMessageBusRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_message_bus_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreateMessageBusRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_message_bus_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__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_message_bus( - parent='parent_value', - message_bus=gce_message_bus.MessageBus(name='name_value'), - message_bus_id='message_bus_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].message_bus - mock_val = gce_message_bus.MessageBus(name='name_value') - assert arg == mock_val - arg = args[0].message_bus_id - mock_val = 'message_bus_id_value' - assert arg == mock_val - - -def test_create_message_bus_flattened_error(): - client = EventarcClient( - credentials=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_message_bus( - eventarc.CreateMessageBusRequest(), - parent='parent_value', - message_bus=gce_message_bus.MessageBus(name='name_value'), - message_bus_id='message_bus_id_value', - ) - -@pytest.mark.asyncio -async def test_create_message_bus_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__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_message_bus( - parent='parent_value', - message_bus=gce_message_bus.MessageBus(name='name_value'), - message_bus_id='message_bus_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].message_bus - mock_val = gce_message_bus.MessageBus(name='name_value') - assert arg == mock_val - arg = args[0].message_bus_id - mock_val = 'message_bus_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_message_bus_flattened_error_async(): - client = EventarcAsyncClient( - 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_message_bus( - eventarc.CreateMessageBusRequest(), - parent='parent_value', - message_bus=gce_message_bus.MessageBus(name='name_value'), - message_bus_id='message_bus_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateMessageBusRequest, - dict, -]) -def test_update_message_bus(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateMessageBusRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_message_bus_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 = EventarcClient( - 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 = eventarc.UpdateMessageBusRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_message_bus(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdateMessageBusRequest( - ) - -def test_update_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - request = {} - client.update_message_bus(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.update_message_bus(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_message_bus_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 = EventarcAsyncClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - await client.update_message_bus(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.update_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateMessageBusRequest): - client = EventarcAsyncClient( - 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_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateMessageBusRequest() - 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_update_message_bus_async_from_dict(): - await test_update_message_bus_async(request_type=dict) - -def test_update_message_bus_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdateMessageBusRequest() - - request.message_bus.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'message_bus.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_message_bus_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdateMessageBusRequest() - - request.message_bus.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'message_bus.name=name_value', - ) in kw['metadata'] - - -def test_update_message_bus_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_message_bus( - message_bus=gce_message_bus.MessageBus(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].message_bus - mock_val = gce_message_bus.MessageBus(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_message_bus_flattened_error(): - client = EventarcClient( - credentials=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_message_bus( - eventarc.UpdateMessageBusRequest(), - message_bus=gce_message_bus.MessageBus(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_message_bus_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_message_bus( - message_bus=gce_message_bus.MessageBus(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].message_bus - mock_val = gce_message_bus.MessageBus(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_message_bus_flattened_error_async(): - client = EventarcAsyncClient( - 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_message_bus( - eventarc.UpdateMessageBusRequest(), - message_bus=gce_message_bus.MessageBus(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteMessageBusRequest, - dict, -]) -def test_delete_message_bus(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteMessageBusRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_message_bus_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 = EventarcClient( - 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 = eventarc.DeleteMessageBusRequest( - 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_message_bus), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_message_bus(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeleteMessageBusRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - request = {} - client.delete_message_bus(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_message_bus(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_message_bus_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 = EventarcAsyncClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - await client.delete_message_bus(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_message_bus(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_message_bus_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteMessageBusRequest): - client = EventarcAsyncClient( - 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_message_bus), - '__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_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteMessageBusRequest() - 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_message_bus_async_from_dict(): - await test_delete_message_bus_async(request_type=dict) - -def test_delete_message_bus_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeleteMessageBusRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_message_bus_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeleteMessageBusRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_message_bus_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__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_message_bus( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - - -def test_delete_message_bus_flattened_error(): - client = EventarcClient( - credentials=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_message_bus( - eventarc.DeleteMessageBusRequest(), - name='name_value', - etag='etag_value', - ) - -@pytest.mark.asyncio -async def test_delete_message_bus_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__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_message_bus( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_message_bus_flattened_error_async(): - client = EventarcAsyncClient( - 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_message_bus( - eventarc.DeleteMessageBusRequest(), - name='name_value', - etag='etag_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetEnrollmentRequest, - dict, -]) -def test_get_enrollment(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = enrollment.Enrollment( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - cel_match='cel_match_value', - message_bus='message_bus_value', - destination='destination_value', - ) - response = client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetEnrollmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, enrollment.Enrollment) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.cel_match == 'cel_match_value' - assert response.message_bus == 'message_bus_value' - assert response.destination == 'destination_value' - - -def test_get_enrollment_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 = EventarcClient( - 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 = eventarc.GetEnrollmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_enrollment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetEnrollmentRequest( - name='name_value', - ) - -def test_get_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - request = {} - client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_enrollment(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_enrollment_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 = EventarcAsyncClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - await client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetEnrollmentRequest): - client = EventarcAsyncClient( - 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_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - cel_match='cel_match_value', - message_bus='message_bus_value', - destination='destination_value', - )) - response = await client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetEnrollmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, enrollment.Enrollment) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.cel_match == 'cel_match_value' - assert response.message_bus == 'message_bus_value' - assert response.destination == 'destination_value' - - -@pytest.mark.asyncio -async def test_get_enrollment_async_from_dict(): - await test_get_enrollment_async(request_type=dict) - -def test_get_enrollment_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetEnrollmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - call.return_value = enrollment.Enrollment() - client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_enrollment_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetEnrollmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment()) - await client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_enrollment_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = enrollment.Enrollment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_enrollment( - name='name_value', - ) - - # 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_enrollment_flattened_error(): - client = EventarcClient( - credentials=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_enrollment( - eventarc.GetEnrollmentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_enrollment_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = enrollment.Enrollment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_enrollment( - name='name_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_enrollment_flattened_error_async(): - client = EventarcAsyncClient( - 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_enrollment( - eventarc.GetEnrollmentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListEnrollmentsRequest, - dict, -]) -def test_list_enrollments(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListEnrollmentsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListEnrollmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnrollmentsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_enrollments_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 = EventarcClient( - 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 = eventarc.ListEnrollmentsRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_enrollments(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListEnrollmentsRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - -def test_list_enrollments_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 = EventarcClient( - 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_enrollments 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_enrollments] = mock_rpc - request = {} - client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_enrollments(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_enrollments_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 = EventarcAsyncClient( - 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_enrollments 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_enrollments] = mock_rpc - - request = {} - await client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_enrollments(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_enrollments_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListEnrollmentsRequest): - client = EventarcAsyncClient( - 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_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListEnrollmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnrollmentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_enrollments_async_from_dict(): - await test_list_enrollments_async(request_type=dict) - -def test_list_enrollments_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListEnrollmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - call.return_value = eventarc.ListEnrollmentsResponse() - client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_enrollments_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListEnrollmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse()) - await client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_enrollments_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListEnrollmentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_enrollments( - 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_enrollments_flattened_error(): - client = EventarcClient( - credentials=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_enrollments( - eventarc.ListEnrollmentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_enrollments_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListEnrollmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_enrollments( - 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_enrollments_flattened_error_async(): - client = EventarcAsyncClient( - 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_enrollments( - eventarc.ListEnrollmentsRequest(), - parent='parent_value', - ) - - -def test_list_enrollments_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_enrollments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - next_page_token='abc', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - ], - next_page_token='ghi', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_enrollments(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, enrollment.Enrollment) - for i in results) -def test_list_enrollments_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_enrollments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - next_page_token='abc', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - ], - next_page_token='ghi', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_enrollments(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_enrollments_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - next_page_token='abc', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - ], - next_page_token='ghi', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_enrollments(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, enrollment.Enrollment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_enrollments_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - next_page_token='abc', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - ], - next_page_token='ghi', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - ), - 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_enrollments(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", [ - eventarc.CreateEnrollmentRequest, - dict, -]) -def test_create_enrollment(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreateEnrollmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_enrollment_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 = EventarcClient( - 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 = eventarc.CreateEnrollmentRequest( - parent='parent_value', - enrollment_id='enrollment_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_enrollment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreateEnrollmentRequest( - parent='parent_value', - enrollment_id='enrollment_id_value', - ) - -def test_create_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - request = {} - client.create_enrollment(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_enrollment(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_enrollment_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 = EventarcAsyncClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - await client.create_enrollment(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_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateEnrollmentRequest): - client = EventarcAsyncClient( - 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_enrollment), - '__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_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreateEnrollmentRequest() - 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_enrollment_async_from_dict(): - await test_create_enrollment_async(request_type=dict) - -def test_create_enrollment_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreateEnrollmentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_enrollment_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreateEnrollmentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_enrollment_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__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_enrollment( - parent='parent_value', - enrollment=gce_enrollment.Enrollment(name='name_value'), - enrollment_id='enrollment_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].enrollment - mock_val = gce_enrollment.Enrollment(name='name_value') - assert arg == mock_val - arg = args[0].enrollment_id - mock_val = 'enrollment_id_value' - assert arg == mock_val - - -def test_create_enrollment_flattened_error(): - client = EventarcClient( - credentials=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_enrollment( - eventarc.CreateEnrollmentRequest(), - parent='parent_value', - enrollment=gce_enrollment.Enrollment(name='name_value'), - enrollment_id='enrollment_id_value', - ) - -@pytest.mark.asyncio -async def test_create_enrollment_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__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_enrollment( - parent='parent_value', - enrollment=gce_enrollment.Enrollment(name='name_value'), - enrollment_id='enrollment_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].enrollment - mock_val = gce_enrollment.Enrollment(name='name_value') - assert arg == mock_val - arg = args[0].enrollment_id - mock_val = 'enrollment_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_enrollment_flattened_error_async(): - client = EventarcAsyncClient( - 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_enrollment( - eventarc.CreateEnrollmentRequest(), - parent='parent_value', - enrollment=gce_enrollment.Enrollment(name='name_value'), - enrollment_id='enrollment_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateEnrollmentRequest, - dict, -]) -def test_update_enrollment(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateEnrollmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_enrollment_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 = EventarcClient( - 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 = eventarc.UpdateEnrollmentRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_enrollment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdateEnrollmentRequest( - ) - -def test_update_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - request = {} - client.update_enrollment(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.update_enrollment(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_enrollment_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 = EventarcAsyncClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - await client.update_enrollment(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.update_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateEnrollmentRequest): - client = EventarcAsyncClient( - 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_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateEnrollmentRequest() - 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_update_enrollment_async_from_dict(): - await test_update_enrollment_async(request_type=dict) - -def test_update_enrollment_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdateEnrollmentRequest() - - request.enrollment.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'enrollment.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_enrollment_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdateEnrollmentRequest() - - request.enrollment.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'enrollment.name=name_value', - ) in kw['metadata'] - - -def test_update_enrollment_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_enrollment( - enrollment=gce_enrollment.Enrollment(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].enrollment - mock_val = gce_enrollment.Enrollment(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_enrollment_flattened_error(): - client = EventarcClient( - credentials=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_enrollment( - eventarc.UpdateEnrollmentRequest(), - enrollment=gce_enrollment.Enrollment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_enrollment_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_enrollment( - enrollment=gce_enrollment.Enrollment(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].enrollment - mock_val = gce_enrollment.Enrollment(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_enrollment_flattened_error_async(): - client = EventarcAsyncClient( - 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_enrollment( - eventarc.UpdateEnrollmentRequest(), - enrollment=gce_enrollment.Enrollment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteEnrollmentRequest, - dict, -]) -def test_delete_enrollment(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteEnrollmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_enrollment_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 = EventarcClient( - 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 = eventarc.DeleteEnrollmentRequest( - 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_enrollment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_enrollment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeleteEnrollmentRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - request = {} - client.delete_enrollment(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_enrollment(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_enrollment_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 = EventarcAsyncClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - await client.delete_enrollment(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_enrollment(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_enrollment_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteEnrollmentRequest): - client = EventarcAsyncClient( - 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_enrollment), - '__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_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteEnrollmentRequest() - 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_enrollment_async_from_dict(): - await test_delete_enrollment_async(request_type=dict) - -def test_delete_enrollment_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeleteEnrollmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_enrollment_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeleteEnrollmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_enrollment_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__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_enrollment( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - - -def test_delete_enrollment_flattened_error(): - client = EventarcClient( - credentials=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_enrollment( - eventarc.DeleteEnrollmentRequest(), - name='name_value', - etag='etag_value', - ) - -@pytest.mark.asyncio -async def test_delete_enrollment_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__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_enrollment( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_enrollment_flattened_error_async(): - client = EventarcAsyncClient( - 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_enrollment( - eventarc.DeleteEnrollmentRequest(), - name='name_value', - etag='etag_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetPipelineRequest, - dict, -]) -def test_get_pipeline(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pipeline.Pipeline( - name='name_value', - uid='uid_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - etag='etag_value', - ) - response = client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetPipelineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pipeline.Pipeline) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.display_name == 'display_name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.etag == 'etag_value' - - -def test_get_pipeline_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 = EventarcClient( - 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 = eventarc.GetPipelineRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_pipeline(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetPipelineRequest( - name='name_value', - ) - -def test_get_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - request = {} - client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_pipeline(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_pipeline_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 = EventarcAsyncClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - await client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetPipelineRequest): - client = EventarcAsyncClient( - 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_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline( - name='name_value', - uid='uid_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - etag='etag_value', - )) - response = await client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetPipelineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pipeline.Pipeline) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.display_name == 'display_name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_pipeline_async_from_dict(): - await test_get_pipeline_async(request_type=dict) - -def test_get_pipeline_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetPipelineRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - call.return_value = pipeline.Pipeline() - client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_pipeline_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetPipelineRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline()) - await client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_pipeline_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pipeline.Pipeline() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_pipeline( - name='name_value', - ) - - # 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_pipeline_flattened_error(): - client = EventarcClient( - credentials=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_pipeline( - eventarc.GetPipelineRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_pipeline_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pipeline.Pipeline() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_pipeline( - name='name_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_pipeline_flattened_error_async(): - client = EventarcAsyncClient( - 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_pipeline( - eventarc.GetPipelineRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListPipelinesRequest, - dict, -]) -def test_list_pipelines(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListPipelinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListPipelinesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPipelinesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_pipelines_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 = EventarcClient( - 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 = eventarc.ListPipelinesRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_pipelines(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListPipelinesRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - -def test_list_pipelines_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 = EventarcClient( - 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_pipelines 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_pipelines] = mock_rpc - request = {} - client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_pipelines(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_pipelines_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 = EventarcAsyncClient( - 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_pipelines 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_pipelines] = mock_rpc - - request = {} - await client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_pipelines(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_pipelines_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListPipelinesRequest): - client = EventarcAsyncClient( - 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_pipelines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListPipelinesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPipelinesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_pipelines_async_from_dict(): - await test_list_pipelines_async(request_type=dict) - -def test_list_pipelines_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListPipelinesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - call.return_value = eventarc.ListPipelinesResponse() - client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_pipelines_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListPipelinesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse()) - await client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_pipelines_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListPipelinesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_pipelines( - 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_pipelines_flattened_error(): - client = EventarcClient( - credentials=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_pipelines( - eventarc.ListPipelinesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_pipelines_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListPipelinesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_pipelines( - 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_pipelines_flattened_error_async(): - client = EventarcAsyncClient( - 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_pipelines( - eventarc.ListPipelinesRequest(), - parent='parent_value', - ) - - -def test_list_pipelines_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_pipelines), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - next_page_token='abc', - ), - eventarc.ListPipelinesResponse( - pipelines=[], - next_page_token='def', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - ], - next_page_token='ghi', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_pipelines(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, pipeline.Pipeline) - for i in results) -def test_list_pipelines_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_pipelines), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - next_page_token='abc', - ), - eventarc.ListPipelinesResponse( - pipelines=[], - next_page_token='def', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - ], - next_page_token='ghi', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - ), - RuntimeError, - ) - pages = list(client.list_pipelines(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_pipelines_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - next_page_token='abc', - ), - eventarc.ListPipelinesResponse( - pipelines=[], - next_page_token='def', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - ], - next_page_token='ghi', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_pipelines(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, pipeline.Pipeline) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_pipelines_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - next_page_token='abc', - ), - eventarc.ListPipelinesResponse( - pipelines=[], - next_page_token='def', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - ], - next_page_token='ghi', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - ), - 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_pipelines(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", [ - eventarc.CreatePipelineRequest, - dict, -]) -def test_create_pipeline(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreatePipelineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_pipeline_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 = EventarcClient( - 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 = eventarc.CreatePipelineRequest( - parent='parent_value', - pipeline_id='pipeline_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_pipeline(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreatePipelineRequest( - parent='parent_value', - pipeline_id='pipeline_id_value', - ) - -def test_create_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - request = {} - client.create_pipeline(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_pipeline(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_pipeline_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 = EventarcAsyncClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - await client.create_pipeline(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_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreatePipelineRequest): - client = EventarcAsyncClient( - 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_pipeline), - '__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_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreatePipelineRequest() - 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_pipeline_async_from_dict(): - await test_create_pipeline_async(request_type=dict) - -def test_create_pipeline_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreatePipelineRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_pipeline_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreatePipelineRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_pipeline_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__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_pipeline( - parent='parent_value', - pipeline=gce_pipeline.Pipeline(name='name_value'), - pipeline_id='pipeline_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].pipeline - mock_val = gce_pipeline.Pipeline(name='name_value') - assert arg == mock_val - arg = args[0].pipeline_id - mock_val = 'pipeline_id_value' - assert arg == mock_val - - -def test_create_pipeline_flattened_error(): - client = EventarcClient( - credentials=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_pipeline( - eventarc.CreatePipelineRequest(), - parent='parent_value', - pipeline=gce_pipeline.Pipeline(name='name_value'), - pipeline_id='pipeline_id_value', - ) - -@pytest.mark.asyncio -async def test_create_pipeline_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__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_pipeline( - parent='parent_value', - pipeline=gce_pipeline.Pipeline(name='name_value'), - pipeline_id='pipeline_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].pipeline - mock_val = gce_pipeline.Pipeline(name='name_value') - assert arg == mock_val - arg = args[0].pipeline_id - mock_val = 'pipeline_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_pipeline_flattened_error_async(): - client = EventarcAsyncClient( - 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_pipeline( - eventarc.CreatePipelineRequest(), - parent='parent_value', - pipeline=gce_pipeline.Pipeline(name='name_value'), - pipeline_id='pipeline_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdatePipelineRequest, - dict, -]) -def test_update_pipeline(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdatePipelineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_pipeline_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 = EventarcClient( - 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 = eventarc.UpdatePipelineRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_pipeline(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdatePipelineRequest( - ) - -def test_update_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - request = {} - client.update_pipeline(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.update_pipeline(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_pipeline_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 = EventarcAsyncClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - await client.update_pipeline(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.update_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdatePipelineRequest): - client = EventarcAsyncClient( - 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_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdatePipelineRequest() - 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_update_pipeline_async_from_dict(): - await test_update_pipeline_async(request_type=dict) - -def test_update_pipeline_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdatePipelineRequest() - - request.pipeline.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'pipeline.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_pipeline_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdatePipelineRequest() - - request.pipeline.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'pipeline.name=name_value', - ) in kw['metadata'] - - -def test_update_pipeline_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_pipeline( - pipeline=gce_pipeline.Pipeline(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].pipeline - mock_val = gce_pipeline.Pipeline(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_pipeline_flattened_error(): - client = EventarcClient( - credentials=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_pipeline( - eventarc.UpdatePipelineRequest(), - pipeline=gce_pipeline.Pipeline(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_pipeline_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_pipeline( - pipeline=gce_pipeline.Pipeline(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].pipeline - mock_val = gce_pipeline.Pipeline(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_pipeline_flattened_error_async(): - client = EventarcAsyncClient( - 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_pipeline( - eventarc.UpdatePipelineRequest(), - pipeline=gce_pipeline.Pipeline(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeletePipelineRequest, - dict, -]) -def test_delete_pipeline(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeletePipelineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_pipeline_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 = EventarcClient( - 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 = eventarc.DeletePipelineRequest( - 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_pipeline), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_pipeline(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeletePipelineRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - request = {} - client.delete_pipeline(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_pipeline(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_pipeline_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 = EventarcAsyncClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - await client.delete_pipeline(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_pipeline(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_pipeline_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeletePipelineRequest): - client = EventarcAsyncClient( - 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_pipeline), - '__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_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeletePipelineRequest() - 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_pipeline_async_from_dict(): - await test_delete_pipeline_async(request_type=dict) - -def test_delete_pipeline_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeletePipelineRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_pipeline_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeletePipelineRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_pipeline_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__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_pipeline( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - - -def test_delete_pipeline_flattened_error(): - client = EventarcClient( - credentials=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_pipeline( - eventarc.DeletePipelineRequest(), - name='name_value', - etag='etag_value', - ) - -@pytest.mark.asyncio -async def test_delete_pipeline_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__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_pipeline( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_pipeline_flattened_error_async(): - client = EventarcAsyncClient( - 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_pipeline( - eventarc.DeletePipelineRequest(), - name='name_value', - etag='etag_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetGoogleApiSourceRequest, - dict, -]) -def test_get_google_api_source(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = google_api_source.GoogleApiSource( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - destination='destination_value', - crypto_key_name='crypto_key_name_value', - ) - response = client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.GetGoogleApiSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, google_api_source.GoogleApiSource) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.destination == 'destination_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -def test_get_google_api_source_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 = EventarcClient( - 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 = eventarc.GetGoogleApiSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_google_api_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.GetGoogleApiSourceRequest( - name='name_value', - ) - -def test_get_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - request = {} - client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_google_api_source(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_google_api_source_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 = EventarcAsyncClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - await client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.GetGoogleApiSourceRequest): - client = EventarcAsyncClient( - 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_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - destination='destination_value', - crypto_key_name='crypto_key_name_value', - )) - response = await client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.GetGoogleApiSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, google_api_source.GoogleApiSource) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.destination == 'destination_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.asyncio -async def test_get_google_api_source_async_from_dict(): - await test_get_google_api_source_async(request_type=dict) - -def test_get_google_api_source_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.GetGoogleApiSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - call.return_value = google_api_source.GoogleApiSource() - client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_google_api_source_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.GetGoogleApiSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource()) - await client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_google_api_source_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = google_api_source.GoogleApiSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_google_api_source( - name='name_value', - ) - - # 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_google_api_source_flattened_error(): - client = EventarcClient( - credentials=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_google_api_source( - eventarc.GetGoogleApiSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_google_api_source_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = google_api_source.GoogleApiSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_google_api_source( - name='name_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_google_api_source_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_api_source( - eventarc.GetGoogleApiSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListGoogleApiSourcesRequest, - dict, -]) -def test_list_google_api_sources(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListGoogleApiSourcesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.ListGoogleApiSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGoogleApiSourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_google_api_sources_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 = EventarcClient( - 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 = eventarc.ListGoogleApiSourcesRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_google_api_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.ListGoogleApiSourcesRequest( - parent='parent_value', - page_token='page_token_value', - order_by='order_by_value', - filter='filter_value', - ) - -def test_list_google_api_sources_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 = EventarcClient( - 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_google_api_sources 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_google_api_sources] = mock_rpc - request = {} - client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_google_api_sources(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_google_api_sources_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 = EventarcAsyncClient( - 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_google_api_sources 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_google_api_sources] = mock_rpc - - request = {} - await client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_google_api_sources(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_google_api_sources_async(transport: str = 'grpc_asyncio', request_type=eventarc.ListGoogleApiSourcesRequest): - client = EventarcAsyncClient( - 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_google_api_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.ListGoogleApiSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGoogleApiSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_google_api_sources_async_from_dict(): - await test_list_google_api_sources_async(request_type=dict) - -def test_list_google_api_sources_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.ListGoogleApiSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - call.return_value = eventarc.ListGoogleApiSourcesResponse() - client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_google_api_sources_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.ListGoogleApiSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse()) - await client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_google_api_sources_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListGoogleApiSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_google_api_sources( - 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_google_api_sources_flattened_error(): - client = EventarcClient( - credentials=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_google_api_sources( - eventarc.ListGoogleApiSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_google_api_sources_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = eventarc.ListGoogleApiSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_google_api_sources( - 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_google_api_sources_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_api_sources( - eventarc.ListGoogleApiSourcesRequest(), - parent='parent_value', - ) - - -def test_list_google_api_sources_pager(transport_name: str = "grpc"): - client = EventarcClient( - 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_google_api_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - next_page_token='abc', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[], - next_page_token='def', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - ], - next_page_token='ghi', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_google_api_sources(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, google_api_source.GoogleApiSource) - for i in results) -def test_list_google_api_sources_pages(transport_name: str = "grpc"): - client = EventarcClient( - 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_google_api_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - next_page_token='abc', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[], - next_page_token='def', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - ], - next_page_token='ghi', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_google_api_sources(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_google_api_sources_async_pager(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - next_page_token='abc', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[], - next_page_token='def', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - ], - next_page_token='ghi', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_google_api_sources(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, google_api_source.GoogleApiSource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_google_api_sources_async_pages(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - next_page_token='abc', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[], - next_page_token='def', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - ], - next_page_token='ghi', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - ), - 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_google_api_sources(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", [ - eventarc.CreateGoogleApiSourceRequest, - dict, -]) -def test_create_google_api_source(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.CreateGoogleApiSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_google_api_source_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 = EventarcClient( - 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 = eventarc.CreateGoogleApiSourceRequest( - parent='parent_value', - google_api_source_id='google_api_source_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_google_api_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.CreateGoogleApiSourceRequest( - parent='parent_value', - google_api_source_id='google_api_source_id_value', - ) - -def test_create_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - request = {} - client.create_google_api_source(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_google_api_source(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_google_api_source_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 = EventarcAsyncClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - await client.create_google_api_source(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_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.CreateGoogleApiSourceRequest): - client = EventarcAsyncClient( - 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_google_api_source), - '__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_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.CreateGoogleApiSourceRequest() - 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_google_api_source_async_from_dict(): - await test_create_google_api_source_async(request_type=dict) - -def test_create_google_api_source_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.CreateGoogleApiSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_google_api_source_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.CreateGoogleApiSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_google_api_source_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__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_google_api_source( - parent='parent_value', - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - google_api_source_id='google_api_source_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].google_api_source - mock_val = gce_google_api_source.GoogleApiSource(name='name_value') - assert arg == mock_val - arg = args[0].google_api_source_id - mock_val = 'google_api_source_id_value' - assert arg == mock_val - - -def test_create_google_api_source_flattened_error(): - client = EventarcClient( - credentials=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_google_api_source( - eventarc.CreateGoogleApiSourceRequest(), - parent='parent_value', - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - google_api_source_id='google_api_source_id_value', - ) - -@pytest.mark.asyncio -async def test_create_google_api_source_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__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_google_api_source( - parent='parent_value', - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - google_api_source_id='google_api_source_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].google_api_source - mock_val = gce_google_api_source.GoogleApiSource(name='name_value') - assert arg == mock_val - arg = args[0].google_api_source_id - mock_val = 'google_api_source_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_google_api_source_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_api_source( - eventarc.CreateGoogleApiSourceRequest(), - parent='parent_value', - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - google_api_source_id='google_api_source_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateGoogleApiSourceRequest, - dict, -]) -def test_update_google_api_source(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateGoogleApiSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_google_api_source_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 = EventarcClient( - 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 = eventarc.UpdateGoogleApiSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_google_api_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.UpdateGoogleApiSourceRequest( - ) - -def test_update_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - request = {} - client.update_google_api_source(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.update_google_api_source(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_google_api_source_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 = EventarcAsyncClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - await client.update_google_api_source(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.update_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.UpdateGoogleApiSourceRequest): - client = EventarcAsyncClient( - 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_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.UpdateGoogleApiSourceRequest() - 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_update_google_api_source_async_from_dict(): - await test_update_google_api_source_async(request_type=dict) - -def test_update_google_api_source_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.UpdateGoogleApiSourceRequest() - - request.google_api_source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'google_api_source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_google_api_source_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.UpdateGoogleApiSourceRequest() - - request.google_api_source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'google_api_source.name=name_value', - ) in kw['metadata'] - - -def test_update_google_api_source_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_google_api_source( - google_api_source=gce_google_api_source.GoogleApiSource(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].google_api_source - mock_val = gce_google_api_source.GoogleApiSource(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_google_api_source_flattened_error(): - client = EventarcClient( - credentials=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_google_api_source( - eventarc.UpdateGoogleApiSourceRequest(), - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_google_api_source_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_google_api_source( - google_api_source=gce_google_api_source.GoogleApiSource(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].google_api_source - mock_val = gce_google_api_source.GoogleApiSource(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_google_api_source_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_api_source( - eventarc.UpdateGoogleApiSourceRequest(), - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteGoogleApiSourceRequest, - dict, -]) -def test_delete_google_api_source(request_type, transport: str = 'grpc'): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteGoogleApiSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_google_api_source_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 = EventarcClient( - 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 = eventarc.DeleteGoogleApiSourceRequest( - 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_google_api_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_google_api_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == eventarc.DeleteGoogleApiSourceRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - request = {} - client.delete_google_api_source(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_google_api_source(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_google_api_source_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 = EventarcAsyncClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - await client.delete_google_api_source(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_google_api_source(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_google_api_source_async(transport: str = 'grpc_asyncio', request_type=eventarc.DeleteGoogleApiSourceRequest): - client = EventarcAsyncClient( - 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_google_api_source), - '__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_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = eventarc.DeleteGoogleApiSourceRequest() - 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_google_api_source_async_from_dict(): - await test_delete_google_api_source_async(request_type=dict) - -def test_delete_google_api_source_field_headers(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = eventarc.DeleteGoogleApiSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_google_api_source_field_headers_async(): - client = EventarcAsyncClient( - 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 = eventarc.DeleteGoogleApiSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_google_api_source_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__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_google_api_source( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - - -def test_delete_google_api_source_flattened_error(): - client = EventarcClient( - credentials=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_google_api_source( - eventarc.DeleteGoogleApiSourceRequest(), - name='name_value', - etag='etag_value', - ) - -@pytest.mark.asyncio -async def test_delete_google_api_source_flattened_async(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__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_google_api_source( - name='name_value', - etag='etag_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].etag - mock_val = 'etag_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_google_api_source_flattened_error_async(): - client = EventarcAsyncClient( - 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_google_api_source( - eventarc.DeleteGoogleApiSourceRequest(), - name='name_value', - etag='etag_value', - ) - - -def test_get_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - client.get_trigger(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_trigger(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_trigger_rest_required_fields(request_type=eventarc.GetTriggerRequest): - transport_class = transports.EventarcRestTransport - - 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_trigger._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_trigger._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = trigger.Trigger() - # 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 = trigger.Trigger.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 - - response = client.get_trigger(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_trigger._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_trigger_rest_flattened(): - client = EventarcClient( - 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 = trigger.Trigger() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/triggers/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 = trigger.Trigger.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 - - client.get_trigger(**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/*/triggers/*}" % client.transport._host, args[1]) - - -def test_get_trigger_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_trigger( - eventarc.GetTriggerRequest(), - name='name_value', - ) - - -def test_list_triggers_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 = EventarcClient( - 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_triggers 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_triggers] = mock_rpc - - request = {} - client.list_triggers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_triggers(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_triggers_rest_required_fields(request_type=eventarc.ListTriggersRequest): - transport_class = transports.EventarcRestTransport - - 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_triggers._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_triggers._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", )) - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListTriggersResponse() - # 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 = eventarc.ListTriggersResponse.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 - - response = client.list_triggers(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_triggers_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_triggers._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_triggers_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListTriggersResponse() - - # 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 = eventarc.ListTriggersResponse.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 - - client.list_triggers(**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/*}/triggers" % client.transport._host, args[1]) - - -def test_list_triggers_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_triggers( - eventarc.ListTriggersRequest(), - parent='parent_value', - ) - - -def test_list_triggers_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - trigger.Trigger(), - ], - next_page_token='abc', - ), - eventarc.ListTriggersResponse( - triggers=[], - next_page_token='def', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - ], - next_page_token='ghi', - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListTriggersResponse.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_triggers(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, trigger.Trigger) - for i in results) - - pages = list(client.list_triggers(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - client.create_trigger(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_trigger(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_trigger_rest_required_fields(request_type=eventarc.CreateTriggerRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["trigger_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 "triggerId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_trigger._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "triggerId" in jsonified_request - assert jsonified_request["triggerId"] == request_init["trigger_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["triggerId"] = 'trigger_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_trigger._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("trigger_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 "triggerId" in jsonified_request - assert jsonified_request["triggerId"] == 'trigger_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_trigger(request) - - expected_params = [ - ( - "triggerId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_trigger._get_unset_required_fields({}) - assert set(unset_fields) == (set(("triggerId", "validateOnly", )) & set(("parent", "trigger", "triggerId", ))) - - -def test_create_trigger_rest_flattened(): - client = EventarcClient( - 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', - trigger=gce_trigger.Trigger(name='name_value'), - trigger_id='trigger_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 - - client.create_trigger(**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/*}/triggers" % client.transport._host, args[1]) - - -def test_create_trigger_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_trigger( - eventarc.CreateTriggerRequest(), - parent='parent_value', - trigger=gce_trigger.Trigger(name='name_value'), - trigger_id='trigger_id_value', - ) - - -def test_update_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - client.update_trigger(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.update_trigger(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_trigger_rest_flattened(): - client = EventarcClient( - 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 = {'trigger': {'name': 'projects/sample1/locations/sample2/triggers/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - trigger=gce_trigger.Trigger(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - allow_missing=True, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_trigger(**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/{trigger.name=projects/*/locations/*/triggers/*}" % client.transport._host, args[1]) - - -def test_update_trigger_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_trigger( - eventarc.UpdateTriggerRequest(), - trigger=gce_trigger.Trigger(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - allow_missing=True, - ) - - -def test_delete_trigger_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 = EventarcClient( - 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_trigger 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_trigger] = mock_rpc - - request = {} - client.delete_trigger(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_trigger(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_trigger_rest_required_fields(request_type=eventarc.DeleteTriggerRequest): - transport_class = transports.EventarcRestTransport - - 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_trigger._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_trigger._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_trigger(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_trigger._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_trigger_rest_flattened(): - client = EventarcClient( - 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/triggers/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - allow_missing=True, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_trigger(**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/*/triggers/*}" % client.transport._host, args[1]) - - -def test_delete_trigger_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_trigger( - eventarc.DeleteTriggerRequest(), - name='name_value', - allow_missing=True, - ) - - -def test_get_channel_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 = EventarcClient( - 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_channel 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_channel] = mock_rpc - - request = {} - client.get_channel(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_channel(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_channel_rest_required_fields(request_type=eventarc.GetChannelRequest): - transport_class = transports.EventarcRestTransport - - 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_channel._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_channel._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = channel.Channel() - # 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 = channel.Channel.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 - - response = client.get_channel(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_channel_rest_flattened(): - client = EventarcClient( - 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 = channel.Channel() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/channels/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 = channel.Channel.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 - - client.get_channel(**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/*/channels/*}" % client.transport._host, args[1]) - - -def test_get_channel_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel( - eventarc.GetChannelRequest(), - name='name_value', - ) - - -def test_list_channels_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 = EventarcClient( - 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_channels 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_channels] = mock_rpc - - request = {} - client.list_channels(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_channels(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_channels_rest_required_fields(request_type=eventarc.ListChannelsRequest): - transport_class = transports.EventarcRestTransport - - 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_channels._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_channels._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("order_by", "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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListChannelsResponse() - # 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 = eventarc.ListChannelsResponse.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 - - response = client.list_channels(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_channels_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_channels._get_unset_required_fields({}) - assert set(unset_fields) == (set(("orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_channels_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListChannelsResponse() - - # 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 = eventarc.ListChannelsResponse.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 - - client.list_channels(**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/*}/channels" % client.transport._host, args[1]) - - -def test_list_channels_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channels( - eventarc.ListChannelsRequest(), - parent='parent_value', - ) - - -def test_list_channels_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - channel.Channel(), - ], - next_page_token='abc', - ), - eventarc.ListChannelsResponse( - channels=[], - next_page_token='def', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListChannelsResponse.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_channels(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, channel.Channel) - for i in results) - - pages = list(client.list_channels(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_channel_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 = EventarcClient( - 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_channel_ 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_channel_] = mock_rpc - - request = {} - client.create_channel(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_channel(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_channel_rest_required_fields(request_type=eventarc.CreateChannelRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["channel_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 "channelId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "channelId" in jsonified_request - assert jsonified_request["channelId"] == request_init["channel_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["channelId"] = 'channel_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("channel_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 "channelId" in jsonified_request - assert jsonified_request["channelId"] == 'channel_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_channel(request) - - expected_params = [ - ( - "channelId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_channel_._get_unset_required_fields({}) - assert set(unset_fields) == (set(("channelId", "validateOnly", )) & set(("parent", "channel", "channelId", ))) - - -def test_create_channel_rest_flattened(): - client = EventarcClient( - 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', - channel=gce_channel.Channel(name='name_value'), - channel_id='channel_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 - - client.create_channel(**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/*}/channels" % client.transport._host, args[1]) - - -def test_create_channel_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel( - eventarc.CreateChannelRequest(), - parent='parent_value', - channel=gce_channel.Channel(name='name_value'), - channel_id='channel_id_value', - ) - - -def test_update_channel_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 = EventarcClient( - 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_channel 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_channel] = mock_rpc - - request = {} - client.update_channel(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.update_channel(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_channel_rest_flattened(): - client = EventarcClient( - 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 = {'channel': {'name': 'projects/sample1/locations/sample2/channels/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - channel=gce_channel.Channel(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_channel(**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/{channel.name=projects/*/locations/*/channels/*}" % client.transport._host, args[1]) - - -def test_update_channel_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel( - eventarc.UpdateChannelRequest(), - channel=gce_channel.Channel(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_channel_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 = EventarcClient( - 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_channel 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_channel] = mock_rpc - - request = {} - client.delete_channel(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_channel(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_channel_rest_required_fields(request_type=eventarc.DeleteChannelRequest): - transport_class = transports.EventarcRestTransport - - 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_channel._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_channel._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_channel(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", )) & set(("name", ))) - - -def test_delete_channel_rest_flattened(): - client = EventarcClient( - 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/channels/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_channel(**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/*/channels/*}" % client.transport._host, args[1]) - - -def test_delete_channel_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel( - eventarc.DeleteChannelRequest(), - name='name_value', - ) - - -def test_get_provider_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 = EventarcClient( - 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_provider 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_provider] = mock_rpc - - request = {} - client.get_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_provider(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_provider_rest_required_fields(request_type=eventarc.GetProviderRequest): - transport_class = transports.EventarcRestTransport - - 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_provider._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_provider._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = discovery.Provider() - # 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 = discovery.Provider.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 - - response = client.get_provider(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_provider_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_provider._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_provider_rest_flattened(): - client = EventarcClient( - 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 = discovery.Provider() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/providers/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 = discovery.Provider.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 - - client.get_provider(**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/*/providers/*}" % client.transport._host, args[1]) - - -def test_get_provider_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_provider( - eventarc.GetProviderRequest(), - name='name_value', - ) - - -def test_list_providers_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 = EventarcClient( - 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_providers 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_providers] = mock_rpc - - request = {} - client.list_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_providers(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_providers_rest_required_fields(request_type=eventarc.ListProvidersRequest): - transport_class = transports.EventarcRestTransport - - 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_providers._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_providers._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", )) - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListProvidersResponse() - # 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 = eventarc.ListProvidersResponse.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 - - response = client.list_providers(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_providers_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_providers._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_providers_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListProvidersResponse() - - # 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 = eventarc.ListProvidersResponse.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 - - client.list_providers(**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/*}/providers" % client.transport._host, args[1]) - - -def test_list_providers_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_providers( - eventarc.ListProvidersRequest(), - parent='parent_value', - ) - - -def test_list_providers_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - discovery.Provider(), - ], - next_page_token='abc', - ), - eventarc.ListProvidersResponse( - providers=[], - next_page_token='def', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - ], - next_page_token='ghi', - ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListProvidersResponse.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_providers(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, discovery.Provider) - for i in results) - - pages = list(client.list_providers(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_channel_connection_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 = EventarcClient( - 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_channel_connection 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_channel_connection] = mock_rpc - - request = {} - client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_channel_connection(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_channel_connection_rest_required_fields(request_type=eventarc.GetChannelConnectionRequest): - transport_class = transports.EventarcRestTransport - - 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_channel_connection._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_channel_connection._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = channel_connection.ChannelConnection() - # 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 = channel_connection.ChannelConnection.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 - - response = client.get_channel_connection(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_channel_connection_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_channel_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_channel_connection_rest_flattened(): - client = EventarcClient( - 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 = channel_connection.ChannelConnection() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/channelConnections/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 = channel_connection.ChannelConnection.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 - - client.get_channel_connection(**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/*/channelConnections/*}" % client.transport._host, args[1]) - - -def test_get_channel_connection_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel_connection( - eventarc.GetChannelConnectionRequest(), - name='name_value', - ) - - -def test_list_channel_connections_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 = EventarcClient( - 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_channel_connections 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_channel_connections] = mock_rpc - - request = {} - client.list_channel_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_channel_connections(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_channel_connections_rest_required_fields(request_type=eventarc.ListChannelConnectionsRequest): - transport_class = transports.EventarcRestTransport - - 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_channel_connections._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_channel_connections._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListChannelConnectionsResponse() - # 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 = eventarc.ListChannelConnectionsResponse.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 - - response = client.list_channel_connections(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_channel_connections_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_channel_connections._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_channel_connections_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListChannelConnectionsResponse() - - # 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 = eventarc.ListChannelConnectionsResponse.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 - - client.list_channel_connections(**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/*}/channelConnections" % client.transport._host, args[1]) - - -def test_list_channel_connections_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel_connections( - eventarc.ListChannelConnectionsRequest(), - parent='parent_value', - ) - - -def test_list_channel_connections_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - next_page_token='abc', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[], - next_page_token='def', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - ], - next_page_token='ghi', - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListChannelConnectionsResponse.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_channel_connections(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, channel_connection.ChannelConnection) - for i in results) - - pages = list(client.list_channel_connections(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_channel_connection_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 = EventarcClient( - 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_channel_connection 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_channel_connection] = mock_rpc - - request = {} - client.create_channel_connection(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_channel_connection(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_channel_connection_rest_required_fields(request_type=eventarc.CreateChannelConnectionRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["channel_connection_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 "channelConnectionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "channelConnectionId" in jsonified_request - assert jsonified_request["channelConnectionId"] == request_init["channel_connection_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["channelConnectionId"] = 'channel_connection_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_channel_connection._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("channel_connection_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "channelConnectionId" in jsonified_request - assert jsonified_request["channelConnectionId"] == 'channel_connection_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_channel_connection(request) - - expected_params = [ - ( - "channelConnectionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_channel_connection_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_channel_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(("channelConnectionId", )) & set(("parent", "channelConnection", "channelConnectionId", ))) - - -def test_create_channel_connection_rest_flattened(): - client = EventarcClient( - 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', - channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), - channel_connection_id='channel_connection_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 - - client.create_channel_connection(**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/*}/channelConnections" % client.transport._host, args[1]) - - -def test_create_channel_connection_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel_connection( - eventarc.CreateChannelConnectionRequest(), - parent='parent_value', - channel_connection=gce_channel_connection.ChannelConnection(name='name_value'), - channel_connection_id='channel_connection_id_value', - ) - - -def test_delete_channel_connection_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 = EventarcClient( - 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_channel_connection 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_channel_connection] = mock_rpc - - request = {} - client.delete_channel_connection(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_channel_connection(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_channel_connection_rest_required_fields(request_type=eventarc.DeleteChannelConnectionRequest): - transport_class = transports.EventarcRestTransport - - 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_channel_connection._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_channel_connection._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_channel_connection(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_channel_connection_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_channel_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_channel_connection_rest_flattened(): - client = EventarcClient( - 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/channelConnections/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_channel_connection(**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/*/channelConnections/*}" % client.transport._host, args[1]) - - -def test_delete_channel_connection_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_channel_connection( - eventarc.DeleteChannelConnectionRequest(), - name='name_value', - ) - - -def test_get_google_channel_config_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 = EventarcClient( - 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_google_channel_config 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_google_channel_config] = mock_rpc - - request = {} - client.get_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_google_channel_config(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_google_channel_config_rest_required_fields(request_type=eventarc.GetGoogleChannelConfigRequest): - transport_class = transports.EventarcRestTransport - - 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_google_channel_config._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_google_channel_config._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = google_channel_config.GoogleChannelConfig() - # 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 = google_channel_config.GoogleChannelConfig.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 - - response = client.get_google_channel_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_google_channel_config_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_google_channel_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_google_channel_config_rest_flattened(): - client = EventarcClient( - 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 = google_channel_config.GoogleChannelConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/googleChannelConfig'} - - # 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 = google_channel_config.GoogleChannelConfig.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 - - client.get_google_channel_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/googleChannelConfig}" % client.transport._host, args[1]) - - -def test_get_google_channel_config_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_channel_config( - eventarc.GetGoogleChannelConfigRequest(), - name='name_value', - ) - - -def test_update_google_channel_config_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 = EventarcClient( - 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_google_channel_config 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_google_channel_config] = mock_rpc - - request = {} - client.update_google_channel_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_google_channel_config(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_google_channel_config_rest_required_fields(request_type=eventarc.UpdateGoogleChannelConfigRequest): - transport_class = transports.EventarcRestTransport - - 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_google_channel_config._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_google_channel_config._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gce_google_channel_config.GoogleChannelConfig() - # 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 = gce_google_channel_config.GoogleChannelConfig.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 - - response = client.update_google_channel_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_google_channel_config_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_google_channel_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("googleChannelConfig", ))) - - -def test_update_google_channel_config_rest_flattened(): - client = EventarcClient( - 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 = gce_google_channel_config.GoogleChannelConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'google_channel_config': {'name': 'projects/sample1/locations/sample2/googleChannelConfig'}} - - # get truthy value for each flattened field - mock_args = dict( - google_channel_config=gce_google_channel_config.GoogleChannelConfig(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 = gce_google_channel_config.GoogleChannelConfig.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 - - client.update_google_channel_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}" % client.transport._host, args[1]) - - -def test_update_google_channel_config_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_channel_config( - eventarc.UpdateGoogleChannelConfigRequest(), - google_channel_config=gce_google_channel_config.GoogleChannelConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - client.get_message_bus(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.GetMessageBusRequest): - transport_class = transports.EventarcRestTransport - - 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_message_bus._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_message_bus._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = message_bus.MessageBus() - # 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 = message_bus.MessageBus.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 - - response = client.get_message_bus(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_message_bus_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_message_bus._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_message_bus_rest_flattened(): - client = EventarcClient( - 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 = message_bus.MessageBus() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/messageBuses/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 = message_bus.MessageBus.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 - - client.get_message_bus(**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/*/messageBuses/*}" % client.transport._host, args[1]) - - -def test_get_message_bus_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_message_bus( - eventarc.GetMessageBusRequest(), - name='name_value', - ) - - -def test_list_message_buses_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 = EventarcClient( - 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_message_buses 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_message_buses] = mock_rpc - - request = {} - client.list_message_buses(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_message_buses(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_message_buses_rest_required_fields(request_type=eventarc.ListMessageBusesRequest): - transport_class = transports.EventarcRestTransport - - 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_message_buses._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_message_buses._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", )) - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListMessageBusesResponse() - # 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 = eventarc.ListMessageBusesResponse.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 - - response = client.list_message_buses(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_message_buses_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_message_buses._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_message_buses_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListMessageBusesResponse() - - # 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 = eventarc.ListMessageBusesResponse.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 - - client.list_message_buses(**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/*}/messageBuses" % client.transport._host, args[1]) - - -def test_list_message_buses_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_message_buses( - eventarc.ListMessageBusesRequest(), - parent='parent_value', - ) - - -def test_list_message_buses_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusesResponse( - message_buses=[], - next_page_token='def', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusesResponse( - message_buses=[ - message_bus.MessageBus(), - message_bus.MessageBus(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListMessageBusesResponse.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_message_buses(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, message_bus.MessageBus) - for i in results) - - pages = list(client.list_message_buses(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_message_bus_enrollments_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 = EventarcClient( - 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_message_bus_enrollments 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_message_bus_enrollments] = mock_rpc - - request = {} - client.list_message_bus_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_message_bus_enrollments(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_message_bus_enrollments_rest_required_fields(request_type=eventarc.ListMessageBusEnrollmentsRequest): - transport_class = transports.EventarcRestTransport - - 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_message_bus_enrollments._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_message_bus_enrollments._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListMessageBusEnrollmentsResponse() - # 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 = eventarc.ListMessageBusEnrollmentsResponse.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 - - response = client.list_message_bus_enrollments(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_message_bus_enrollments_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_message_bus_enrollments._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_message_bus_enrollments_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListMessageBusEnrollmentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/messageBuses/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 = eventarc.ListMessageBusEnrollmentsResponse.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 - - client.list_message_bus_enrollments(**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/*/messageBuses/*}:listEnrollments" % client.transport._host, args[1]) - - -def test_list_message_bus_enrollments_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_message_bus_enrollments( - eventarc.ListMessageBusEnrollmentsRequest(), - parent='parent_value', - ) - - -def test_list_message_bus_enrollments_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - ], - next_page_token='ghi', - ), - eventarc.ListMessageBusEnrollmentsResponse( - enrollments=[ - str(), - str(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListMessageBusEnrollmentsResponse.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/messageBuses/sample3'} - - pager = client.list_message_bus_enrollments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) - - pages = list(client.list_message_bus_enrollments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - client.create_message_bus(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_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.CreateMessageBusRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["message_bus_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 "messageBusId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_message_bus._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "messageBusId" in jsonified_request - assert jsonified_request["messageBusId"] == request_init["message_bus_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["messageBusId"] = 'message_bus_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_message_bus._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("message_bus_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 "messageBusId" in jsonified_request - assert jsonified_request["messageBusId"] == 'message_bus_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_message_bus(request) - - expected_params = [ - ( - "messageBusId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_message_bus_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_message_bus._get_unset_required_fields({}) - assert set(unset_fields) == (set(("messageBusId", "validateOnly", )) & set(("parent", "messageBus", "messageBusId", ))) - - -def test_create_message_bus_rest_flattened(): - client = EventarcClient( - 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', - message_bus=gce_message_bus.MessageBus(name='name_value'), - message_bus_id='message_bus_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 - - client.create_message_bus(**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/*}/messageBuses" % client.transport._host, args[1]) - - -def test_create_message_bus_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_message_bus( - eventarc.CreateMessageBusRequest(), - parent='parent_value', - message_bus=gce_message_bus.MessageBus(name='name_value'), - message_bus_id='message_bus_id_value', - ) - - -def test_update_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - client.update_message_bus(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.update_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.UpdateMessageBusRequest): - transport_class = transports.EventarcRestTransport - - 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_message_bus._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_message_bus._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_message_bus(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_message_bus_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_message_bus._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("messageBus", ))) - - -def test_update_message_bus_rest_flattened(): - client = EventarcClient( - 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 = {'message_bus': {'name': 'projects/sample1/locations/sample2/messageBuses/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - message_bus=gce_message_bus.MessageBus(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_message_bus(**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/{message_bus.name=projects/*/locations/*/messageBuses/*}" % client.transport._host, args[1]) - - -def test_update_message_bus_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_message_bus( - eventarc.UpdateMessageBusRequest(), - message_bus=gce_message_bus.MessageBus(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_message_bus_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 = EventarcClient( - 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_message_bus 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_message_bus] = mock_rpc - - request = {} - client.delete_message_bus(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_message_bus(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_message_bus_rest_required_fields(request_type=eventarc.DeleteMessageBusRequest): - transport_class = transports.EventarcRestTransport - - 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_message_bus._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_message_bus._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_message_bus(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_message_bus_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_message_bus._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_message_bus_rest_flattened(): - client = EventarcClient( - 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/messageBuses/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - etag='etag_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_message_bus(**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/*/messageBuses/*}" % client.transport._host, args[1]) - - -def test_delete_message_bus_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_message_bus( - eventarc.DeleteMessageBusRequest(), - name='name_value', - etag='etag_value', - ) - - -def test_get_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - client.get_enrollment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.GetEnrollmentRequest): - transport_class = transports.EventarcRestTransport - - 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_enrollment._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_enrollment._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = enrollment.Enrollment() - # 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 = enrollment.Enrollment.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 - - response = client.get_enrollment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_enrollment_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_enrollment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_enrollment_rest_flattened(): - client = EventarcClient( - 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 = enrollment.Enrollment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/enrollments/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 = enrollment.Enrollment.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 - - client.get_enrollment(**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/*/enrollments/*}" % client.transport._host, args[1]) - - -def test_get_enrollment_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_enrollment( - eventarc.GetEnrollmentRequest(), - name='name_value', - ) - - -def test_list_enrollments_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 = EventarcClient( - 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_enrollments 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_enrollments] = mock_rpc - - request = {} - client.list_enrollments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_enrollments(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_enrollments_rest_required_fields(request_type=eventarc.ListEnrollmentsRequest): - transport_class = transports.EventarcRestTransport - - 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_enrollments._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_enrollments._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", )) - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListEnrollmentsResponse() - # 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 = eventarc.ListEnrollmentsResponse.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 - - response = client.list_enrollments(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_enrollments_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_enrollments._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_enrollments_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListEnrollmentsResponse() - - # 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 = eventarc.ListEnrollmentsResponse.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 - - client.list_enrollments(**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/*}/enrollments" % client.transport._host, args[1]) - - -def test_list_enrollments_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_enrollments( - eventarc.ListEnrollmentsRequest(), - parent='parent_value', - ) - - -def test_list_enrollments_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - next_page_token='abc', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[], - next_page_token='def', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - ], - next_page_token='ghi', - ), - eventarc.ListEnrollmentsResponse( - enrollments=[ - enrollment.Enrollment(), - enrollment.Enrollment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListEnrollmentsResponse.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_enrollments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, enrollment.Enrollment) - for i in results) - - pages = list(client.list_enrollments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - client.create_enrollment(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_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.CreateEnrollmentRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["enrollment_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 "enrollmentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_enrollment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "enrollmentId" in jsonified_request - assert jsonified_request["enrollmentId"] == request_init["enrollment_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["enrollmentId"] = 'enrollment_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_enrollment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("enrollment_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 "enrollmentId" in jsonified_request - assert jsonified_request["enrollmentId"] == 'enrollment_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_enrollment(request) - - expected_params = [ - ( - "enrollmentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_enrollment_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_enrollment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("enrollmentId", "validateOnly", )) & set(("parent", "enrollment", "enrollmentId", ))) - - -def test_create_enrollment_rest_flattened(): - client = EventarcClient( - 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', - enrollment=gce_enrollment.Enrollment(name='name_value'), - enrollment_id='enrollment_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 - - client.create_enrollment(**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/*}/enrollments" % client.transport._host, args[1]) - - -def test_create_enrollment_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_enrollment( - eventarc.CreateEnrollmentRequest(), - parent='parent_value', - enrollment=gce_enrollment.Enrollment(name='name_value'), - enrollment_id='enrollment_id_value', - ) - - -def test_update_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - client.update_enrollment(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.update_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.UpdateEnrollmentRequest): - transport_class = transports.EventarcRestTransport - - 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_enrollment._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_enrollment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_enrollment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_enrollment_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_enrollment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("enrollment", ))) - - -def test_update_enrollment_rest_flattened(): - client = EventarcClient( - 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 = {'enrollment': {'name': 'projects/sample1/locations/sample2/enrollments/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - enrollment=gce_enrollment.Enrollment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_enrollment(**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/{enrollment.name=projects/*/locations/*/enrollments/*}" % client.transport._host, args[1]) - - -def test_update_enrollment_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_enrollment( - eventarc.UpdateEnrollmentRequest(), - enrollment=gce_enrollment.Enrollment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_enrollment_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 = EventarcClient( - 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_enrollment 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_enrollment] = mock_rpc - - request = {} - client.delete_enrollment(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_enrollment(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_enrollment_rest_required_fields(request_type=eventarc.DeleteEnrollmentRequest): - transport_class = transports.EventarcRestTransport - - 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_enrollment._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_enrollment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_enrollment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_enrollment_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_enrollment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_enrollment_rest_flattened(): - client = EventarcClient( - 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/enrollments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - etag='etag_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_enrollment(**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/*/enrollments/*}" % client.transport._host, args[1]) - - -def test_delete_enrollment_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_enrollment( - eventarc.DeleteEnrollmentRequest(), - name='name_value', - etag='etag_value', - ) - - -def test_get_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - client.get_pipeline(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.GetPipelineRequest): - transport_class = transports.EventarcRestTransport - - 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_pipeline._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_pipeline._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pipeline.Pipeline() - # 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 = pipeline.Pipeline.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 - - response = client.get_pipeline(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_pipeline_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_pipeline._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_pipeline_rest_flattened(): - client = EventarcClient( - 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 = pipeline.Pipeline() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/pipelines/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 = pipeline.Pipeline.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 - - client.get_pipeline(**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/*/pipelines/*}" % client.transport._host, args[1]) - - -def test_get_pipeline_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_pipeline( - eventarc.GetPipelineRequest(), - name='name_value', - ) - - -def test_list_pipelines_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 = EventarcClient( - 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_pipelines 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_pipelines] = mock_rpc - - request = {} - client.list_pipelines(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_pipelines(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_pipelines_rest_required_fields(request_type=eventarc.ListPipelinesRequest): - transport_class = transports.EventarcRestTransport - - 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_pipelines._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_pipelines._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", )) - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListPipelinesResponse() - # 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 = eventarc.ListPipelinesResponse.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 - - response = client.list_pipelines(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_pipelines_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_pipelines._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_pipelines_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListPipelinesResponse() - - # 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 = eventarc.ListPipelinesResponse.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 - - client.list_pipelines(**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/*}/pipelines" % client.transport._host, args[1]) - - -def test_list_pipelines_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_pipelines( - eventarc.ListPipelinesRequest(), - parent='parent_value', - ) - - -def test_list_pipelines_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - next_page_token='abc', - ), - eventarc.ListPipelinesResponse( - pipelines=[], - next_page_token='def', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - ], - next_page_token='ghi', - ), - eventarc.ListPipelinesResponse( - pipelines=[ - pipeline.Pipeline(), - pipeline.Pipeline(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListPipelinesResponse.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_pipelines(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pipeline.Pipeline) - for i in results) - - pages = list(client.list_pipelines(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - client.create_pipeline(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_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.CreatePipelineRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["pipeline_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 "pipelineId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_pipeline._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "pipelineId" in jsonified_request - assert jsonified_request["pipelineId"] == request_init["pipeline_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["pipelineId"] = 'pipeline_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_pipeline._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("pipeline_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 "pipelineId" in jsonified_request - assert jsonified_request["pipelineId"] == 'pipeline_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_pipeline(request) - - expected_params = [ - ( - "pipelineId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_pipeline_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_pipeline._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pipelineId", "validateOnly", )) & set(("parent", "pipeline", "pipelineId", ))) - - -def test_create_pipeline_rest_flattened(): - client = EventarcClient( - 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', - pipeline=gce_pipeline.Pipeline(name='name_value'), - pipeline_id='pipeline_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 - - client.create_pipeline(**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/*}/pipelines" % client.transport._host, args[1]) - - -def test_create_pipeline_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_pipeline( - eventarc.CreatePipelineRequest(), - parent='parent_value', - pipeline=gce_pipeline.Pipeline(name='name_value'), - pipeline_id='pipeline_id_value', - ) - - -def test_update_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - client.update_pipeline(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.update_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.UpdatePipelineRequest): - transport_class = transports.EventarcRestTransport - - 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_pipeline._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_pipeline._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_pipeline(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_pipeline_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_pipeline._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("pipeline", ))) - - -def test_update_pipeline_rest_flattened(): - client = EventarcClient( - 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 = {'pipeline': {'name': 'projects/sample1/locations/sample2/pipelines/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - pipeline=gce_pipeline.Pipeline(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_pipeline(**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/{pipeline.name=projects/*/locations/*/pipelines/*}" % client.transport._host, args[1]) - - -def test_update_pipeline_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_pipeline( - eventarc.UpdatePipelineRequest(), - pipeline=gce_pipeline.Pipeline(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_pipeline_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 = EventarcClient( - 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_pipeline 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_pipeline] = mock_rpc - - request = {} - client.delete_pipeline(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_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.DeletePipelineRequest): - transport_class = transports.EventarcRestTransport - - 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_pipeline._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_pipeline._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_pipeline(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_pipeline_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_pipeline._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_pipeline_rest_flattened(): - client = EventarcClient( - 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/pipelines/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - etag='etag_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_pipeline(**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/*/pipelines/*}" % client.transport._host, args[1]) - - -def test_delete_pipeline_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_pipeline( - eventarc.DeletePipelineRequest(), - name='name_value', - etag='etag_value', - ) - - -def test_get_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - client.get_google_api_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.GetGoogleApiSourceRequest): - transport_class = transports.EventarcRestTransport - - 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_google_api_source._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_google_api_source._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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = google_api_source.GoogleApiSource() - # 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 = google_api_source.GoogleApiSource.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 - - response = client.get_google_api_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_google_api_source_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_google_api_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_google_api_source_rest_flattened(): - client = EventarcClient( - 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 = google_api_source.GoogleApiSource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 = google_api_source.GoogleApiSource.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 - - client.get_google_api_source(**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/*/googleApiSources/*}" % client.transport._host, args[1]) - - -def test_get_google_api_source_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_api_source( - eventarc.GetGoogleApiSourceRequest(), - name='name_value', - ) - - -def test_list_google_api_sources_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 = EventarcClient( - 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_google_api_sources 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_google_api_sources] = mock_rpc - - request = {} - client.list_google_api_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_google_api_sources(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_google_api_sources_rest_required_fields(request_type=eventarc.ListGoogleApiSourcesRequest): - transport_class = transports.EventarcRestTransport - - 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_google_api_sources._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_google_api_sources._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", )) - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListGoogleApiSourcesResponse() - # 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 = eventarc.ListGoogleApiSourcesResponse.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 - - response = client.list_google_api_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_google_api_sources_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_google_api_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_google_api_sources_rest_flattened(): - client = EventarcClient( - 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 = eventarc.ListGoogleApiSourcesResponse() - - # 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 = eventarc.ListGoogleApiSourcesResponse.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 - - client.list_google_api_sources(**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/*}/googleApiSources" % client.transport._host, args[1]) - - -def test_list_google_api_sources_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_api_sources( - eventarc.ListGoogleApiSourcesRequest(), - parent='parent_value', - ) - - -def test_list_google_api_sources_rest_pager(transport: str = 'rest'): - client = EventarcClient( - 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 = ( - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - next_page_token='abc', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[], - next_page_token='def', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - ], - next_page_token='ghi', - ), - eventarc.ListGoogleApiSourcesResponse( - google_api_sources=[ - google_api_source.GoogleApiSource(), - google_api_source.GoogleApiSource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListGoogleApiSourcesResponse.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_google_api_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, google_api_source.GoogleApiSource) - for i in results) - - pages = list(client.list_google_api_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - client.create_google_api_source(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_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.CreateGoogleApiSourceRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["google_api_source_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 "googleApiSourceId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_google_api_source._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "googleApiSourceId" in jsonified_request - assert jsonified_request["googleApiSourceId"] == request_init["google_api_source_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["googleApiSourceId"] = 'google_api_source_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_google_api_source._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("google_api_source_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 "googleApiSourceId" in jsonified_request - assert jsonified_request["googleApiSourceId"] == 'google_api_source_id_value' - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_google_api_source(request) - - expected_params = [ - ( - "googleApiSourceId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_google_api_source_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_google_api_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("googleApiSourceId", "validateOnly", )) & set(("parent", "googleApiSource", "googleApiSourceId", ))) - - -def test_create_google_api_source_rest_flattened(): - client = EventarcClient( - 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', - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - google_api_source_id='google_api_source_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 - - client.create_google_api_source(**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/*}/googleApiSources" % client.transport._host, args[1]) - - -def test_create_google_api_source_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_api_source( - eventarc.CreateGoogleApiSourceRequest(), - parent='parent_value', - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - google_api_source_id='google_api_source_id_value', - ) - - -def test_update_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - client.update_google_api_source(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.update_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.UpdateGoogleApiSourceRequest): - transport_class = transports.EventarcRestTransport - - 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_google_api_source._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_google_api_source._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_google_api_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_google_api_source_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_google_api_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("googleApiSource", ))) - - -def test_update_google_api_source_rest_flattened(): - client = EventarcClient( - 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 = {'google_api_source': {'name': 'projects/sample1/locations/sample2/googleApiSources/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_google_api_source(**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/{google_api_source.name=projects/*/locations/*/googleApiSources/*}" % client.transport._host, args[1]) - - -def test_update_google_api_source_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_api_source( - eventarc.UpdateGoogleApiSourceRequest(), - google_api_source=gce_google_api_source.GoogleApiSource(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_google_api_source_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 = EventarcClient( - 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_google_api_source 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_google_api_source] = mock_rpc - - request = {} - client.delete_google_api_source(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_google_api_source(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_google_api_source_rest_required_fields(request_type=eventarc.DeleteGoogleApiSourceRequest): - transport_class = transports.EventarcRestTransport - - 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_google_api_source._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_google_api_source._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_google_api_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_google_api_source_rest_unset_required_fields(): - transport = transports.EventarcRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_google_api_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "validateOnly", )) & set(("name", ))) - - -def test_delete_google_api_source_rest_flattened(): - client = EventarcClient( - 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/googleApiSources/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - etag='etag_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_google_api_source(**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/*/googleApiSources/*}" % client.transport._host, args[1]) - - -def test_delete_google_api_source_rest_flattened_error(transport: str = 'rest'): - client = EventarcClient( - 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_google_api_source( - eventarc.DeleteGoogleApiSourceRequest(), - name='name_value', - etag='etag_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EventarcClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EventarcClient( - 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 = EventarcClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EventarcClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EventarcClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EventarcGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EventarcGrpcTransport, - transports.EventarcGrpcAsyncIOTransport, - transports.EventarcRestTransport, -]) -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 = EventarcClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EventarcClient( - 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_get_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - call.return_value = trigger.Trigger() - client.get_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetTriggerRequest() - - 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_triggers_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - call.return_value = eventarc.ListTriggersResponse() - client.list_triggers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListTriggersRequest() - - 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_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateTriggerRequest() - - 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_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateTriggerRequest() - - 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_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteTriggerRequest() - - 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_channel_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - call.return_value = channel.Channel() - client.get_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelRequest() - - 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_channels_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - call.return_value = eventarc.ListChannelsResponse() - client.list_channels(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelsRequest() - - 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_channel_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelRequest() - - 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_channel_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateChannelRequest() - - 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_channel_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelRequest() - - 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_provider_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - call.return_value = discovery.Provider() - client.get_provider(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetProviderRequest() - - 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_providers_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - call.return_value = eventarc.ListProvidersResponse() - client.list_providers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListProvidersRequest() - - 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_channel_connection_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - call.return_value = channel_connection.ChannelConnection() - client.get_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelConnectionRequest() - - 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_channel_connections_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - call.return_value = eventarc.ListChannelConnectionsResponse() - client.list_channel_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelConnectionsRequest() - - 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_channel_connection_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelConnectionRequest() - - 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_channel_connection_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelConnectionRequest() - - 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_google_channel_config_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - call.return_value = google_channel_config.GoogleChannelConfig() - client.get_google_channel_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleChannelConfigRequest() - - 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_google_channel_config_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - call.return_value = gce_google_channel_config.GoogleChannelConfig() - client.update_google_channel_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleChannelConfigRequest() - - 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_message_bus_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - call.return_value = message_bus.MessageBus() - client.get_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetMessageBusRequest() - - 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_message_buses_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - call.return_value = eventarc.ListMessageBusesResponse() - client.list_message_buses(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListMessageBusesRequest() - - 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_message_bus_enrollments_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - call.return_value = eventarc.ListMessageBusEnrollmentsResponse() - client.list_message_bus_enrollments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListMessageBusEnrollmentsRequest() - - 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_message_bus_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateMessageBusRequest() - - 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_message_bus_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateMessageBusRequest() - - 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_message_bus_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteMessageBusRequest() - - 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_enrollment_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - call.return_value = enrollment.Enrollment() - client.get_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetEnrollmentRequest() - - 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_enrollments_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - call.return_value = eventarc.ListEnrollmentsResponse() - client.list_enrollments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListEnrollmentsRequest() - - 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_enrollment_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateEnrollmentRequest() - - 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_enrollment_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateEnrollmentRequest() - - 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_enrollment_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteEnrollmentRequest() - - 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_pipeline_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - call.return_value = pipeline.Pipeline() - client.get_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetPipelineRequest() - - 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_pipelines_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - call.return_value = eventarc.ListPipelinesResponse() - client.list_pipelines(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListPipelinesRequest() - - 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_pipeline_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreatePipelineRequest() - - 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_pipeline_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdatePipelineRequest() - - 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_pipeline_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeletePipelineRequest() - - 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_google_api_source_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - call.return_value = google_api_source.GoogleApiSource() - client.get_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleApiSourceRequest() - - 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_google_api_sources_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - call.return_value = eventarc.ListGoogleApiSourcesResponse() - client.list_google_api_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListGoogleApiSourcesRequest() - - 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_google_api_source_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateGoogleApiSourceRequest() - - 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_google_api_source_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleApiSourceRequest() - - 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_google_api_source_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteGoogleApiSourceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = EventarcAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EventarcAsyncClient( - 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_get_trigger_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trigger.Trigger( - name='name_value', - uid='uid_value', - service_account='service_account_value', - channel='channel_value', - event_data_content_type='event_data_content_type_value', - satisfies_pzs=True, - etag='etag_value', - )) - await client.get_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetTriggerRequest() - - 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_triggers_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListTriggersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_triggers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListTriggersRequest() - - 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_trigger_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__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_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateTriggerRequest() - - 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_trigger_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__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.update_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateTriggerRequest() - - 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_trigger_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__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_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteTriggerRequest() - - 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_channel_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel.Channel( - name='name_value', - uid='uid_value', - provider='provider_value', - state=channel.Channel.State.PENDING, - activation_token='activation_token_value', - crypto_key_name='crypto_key_name_value', - satisfies_pzs=True, - )) - await client.get_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelRequest() - - 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_channels_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_channels(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelsRequest() - - 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_channel_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__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_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelRequest() - - 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_channel_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__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.update_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateChannelRequest() - - 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_channel_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__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_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelRequest() - - 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_provider_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(discovery.Provider( - name='name_value', - display_name='display_name_value', - )) - await client.get_provider(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetProviderRequest() - - 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_providers_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListProvidersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_providers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListProvidersRequest() - - 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_channel_connection_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_connection.ChannelConnection( - name='name_value', - uid='uid_value', - channel='channel_value', - activation_token='activation_token_value', - )) - await client.get_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelConnectionRequest() - - 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_channel_connections_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListChannelConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_channel_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelConnectionsRequest() - - 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_channel_connection_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__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_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelConnectionRequest() - - 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_channel_connection_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__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_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelConnectionRequest() - - 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_google_channel_config_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_name_value', - )) - await client.get_google_channel_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleChannelConfigRequest() - - 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_google_channel_config_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gce_google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_name_value', - )) - await client.update_google_channel_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleChannelConfigRequest() - - 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_message_bus_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message_bus.MessageBus( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - )) - await client.get_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetMessageBusRequest() - - 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_message_buses_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_message_buses(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListMessageBusesRequest() - - 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_message_bus_enrollments_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListMessageBusEnrollmentsResponse( - enrollments=['enrollments_value'], - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_message_bus_enrollments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListMessageBusEnrollmentsRequest() - - 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_message_bus_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__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_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateMessageBusRequest() - - 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_message_bus_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__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.update_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateMessageBusRequest() - - 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_message_bus_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__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_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteMessageBusRequest() - - 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_enrollment_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(enrollment.Enrollment( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - cel_match='cel_match_value', - message_bus='message_bus_value', - destination='destination_value', - )) - await client.get_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetEnrollmentRequest() - - 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_enrollments_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListEnrollmentsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_enrollments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListEnrollmentsRequest() - - 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_enrollment_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__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_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateEnrollmentRequest() - - 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_enrollment_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__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.update_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateEnrollmentRequest() - - 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_enrollment_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__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_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteEnrollmentRequest() - - 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_pipeline_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline( - name='name_value', - uid='uid_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - etag='etag_value', - )) - await client.get_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetPipelineRequest() - - 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_pipelines_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListPipelinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_pipelines(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListPipelinesRequest() - - 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_pipeline_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__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_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreatePipelineRequest() - - 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_pipeline_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__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.update_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdatePipelineRequest() - - 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_pipeline_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__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_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeletePipelineRequest() - - 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_google_api_source_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(google_api_source.GoogleApiSource( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - destination='destination_value', - crypto_key_name='crypto_key_name_value', - )) - await client.get_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleApiSourceRequest() - - 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_google_api_sources_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(eventarc.ListGoogleApiSourcesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_google_api_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListGoogleApiSourcesRequest() - - 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_google_api_source_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__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_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateGoogleApiSourceRequest() - - 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_google_api_source_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__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.update_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleApiSourceRequest() - - 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_google_api_source_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__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_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteGoogleApiSourceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = EventarcClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_trigger_rest_bad_request(request_type=eventarc.GetTriggerRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 - client.get_trigger(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetTriggerRequest, - dict, -]) -def test_get_trigger_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 = trigger.Trigger( - name='name_value', - uid='uid_value', - service_account='service_account_value', - channel='channel_value', - event_data_content_type='event_data_content_type_value', - satisfies_pzs=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 = trigger.Trigger.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 - response = client.get_trigger(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, trigger.Trigger) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.service_account == 'service_account_value' - assert response.channel == 'channel_value' - assert response.event_data_content_type == 'event_data_content_type_value' - assert response.satisfies_pzs is True - assert response.etag == 'etag_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_trigger_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_trigger") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_trigger") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetTriggerRequest.pb(eventarc.GetTriggerRequest()) - 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 - return_value = trigger.Trigger.to_json(trigger.Trigger()) - req.return_value.content = return_value - - request = eventarc.GetTriggerRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = trigger.Trigger() - - client.get_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_triggers_rest_bad_request(request_type=eventarc.ListTriggersRequest): - client = EventarcClient( - 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 - client.list_triggers(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListTriggersRequest, - dict, -]) -def test_list_triggers_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListTriggersResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListTriggersResponse.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 - response = client.list_triggers(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTriggersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_triggers_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_triggers") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_triggers") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListTriggersRequest.pb(eventarc.ListTriggersRequest()) - 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 - return_value = eventarc.ListTriggersResponse.to_json(eventarc.ListTriggersResponse()) - req.return_value.content = return_value - - request = eventarc.ListTriggersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListTriggersResponse() - - client.list_triggers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_trigger_rest_bad_request(request_type=eventarc.CreateTriggerRequest): - client = EventarcClient( - 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 - client.create_trigger(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreateTriggerRequest, - dict, -]) -def test_create_trigger_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["trigger"] = {'name': 'name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'event_filters': [{'attribute': 'attribute_value', 'value': 'value_value', 'operator': 'operator_value'}], 'service_account': 'service_account_value', 'destination': {'cloud_run': {'service': 'service_value', 'path': 'path_value', 'region': 'region_value'}, 'cloud_function': 'cloud_function_value', 'gke': {'cluster': 'cluster_value', 'location': 'location_value', 'namespace': 'namespace_value', 'service': 'service_value', 'path': 'path_value'}, 'workflow': 'workflow_value', 'http_endpoint': {'uri': 'uri_value'}, 'network_config': {'network_attachment': 'network_attachment_value'}}, 'transport': {'pubsub': {'topic': 'topic_value', 'subscription': 'subscription_value'}}, 'labels': {}, 'channel': 'channel_value', 'conditions': {}, 'event_data_content_type': 'event_data_content_type_value', 'satisfies_pzs': 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 = eventarc.CreateTriggerRequest.meta.fields["trigger"] - - 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["trigger"].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["trigger"][field])): - del request_init["trigger"][field][i][subfield] - else: - del request_init["trigger"][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 - response = client.create_trigger(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_trigger_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_trigger") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_trigger") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreateTriggerRequest.pb(eventarc.CreateTriggerRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreateTriggerRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_trigger_rest_bad_request(request_type=eventarc.UpdateTriggerRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'trigger': {'name': 'projects/sample1/locations/sample2/triggers/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 - client.update_trigger(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateTriggerRequest, - dict, -]) -def test_update_trigger_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'trigger': {'name': 'projects/sample1/locations/sample2/triggers/sample3'}} - request_init["trigger"] = {'name': 'projects/sample1/locations/sample2/triggers/sample3', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'event_filters': [{'attribute': 'attribute_value', 'value': 'value_value', 'operator': 'operator_value'}], 'service_account': 'service_account_value', 'destination': {'cloud_run': {'service': 'service_value', 'path': 'path_value', 'region': 'region_value'}, 'cloud_function': 'cloud_function_value', 'gke': {'cluster': 'cluster_value', 'location': 'location_value', 'namespace': 'namespace_value', 'service': 'service_value', 'path': 'path_value'}, 'workflow': 'workflow_value', 'http_endpoint': {'uri': 'uri_value'}, 'network_config': {'network_attachment': 'network_attachment_value'}}, 'transport': {'pubsub': {'topic': 'topic_value', 'subscription': 'subscription_value'}}, 'labels': {}, 'channel': 'channel_value', 'conditions': {}, 'event_data_content_type': 'event_data_content_type_value', 'satisfies_pzs': 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 = eventarc.UpdateTriggerRequest.meta.fields["trigger"] - - 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["trigger"].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["trigger"][field])): - del request_init["trigger"][field][i][subfield] - else: - del request_init["trigger"][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 - response = client.update_trigger(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_update_trigger_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_trigger") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_trigger") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateTriggerRequest.pb(eventarc.UpdateTriggerRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdateTriggerRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_trigger_rest_bad_request(request_type=eventarc.DeleteTriggerRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 - client.delete_trigger(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteTriggerRequest, - dict, -]) -def test_delete_trigger_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/triggers/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 - response = client.delete_trigger(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_trigger_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_trigger") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_trigger") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeleteTriggerRequest.pb(eventarc.DeleteTriggerRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeleteTriggerRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_trigger(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_channel_rest_bad_request(request_type=eventarc.GetChannelRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channels/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 - client.get_channel(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetChannelRequest, - dict, -]) -def test_get_channel_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channels/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 = channel.Channel( - name='name_value', - uid='uid_value', - provider='provider_value', - state=channel.Channel.State.PENDING, - activation_token='activation_token_value', - crypto_key_name='crypto_key_name_value', - satisfies_pzs=True, - pubsub_topic='pubsub_topic_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 = channel.Channel.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 - response = client.get_channel(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, channel.Channel) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.provider == 'provider_value' - assert response.state == channel.Channel.State.PENDING - assert response.activation_token == 'activation_token_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.satisfies_pzs is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_channel_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_channel") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_channel") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetChannelRequest.pb(eventarc.GetChannelRequest()) - 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 - return_value = channel.Channel.to_json(channel.Channel()) - req.return_value.content = return_value - - request = eventarc.GetChannelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = channel.Channel() - - client.get_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_channels_rest_bad_request(request_type=eventarc.ListChannelsRequest): - client = EventarcClient( - 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 - client.list_channels(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListChannelsRequest, - dict, -]) -def test_list_channels_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListChannelsResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListChannelsResponse.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 - response = client.list_channels(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_channels_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_channels") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_channels") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListChannelsRequest.pb(eventarc.ListChannelsRequest()) - 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 - return_value = eventarc.ListChannelsResponse.to_json(eventarc.ListChannelsResponse()) - req.return_value.content = return_value - - request = eventarc.ListChannelsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListChannelsResponse() - - client.list_channels(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_channel_rest_bad_request(request_type=eventarc.CreateChannelRequest): - client = EventarcClient( - 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 - client.create_channel(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreateChannelRequest, - dict, -]) -def test_create_channel_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["channel"] = {'name': 'name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'provider': 'provider_value', 'pubsub_topic': 'pubsub_topic_value', 'state': 1, 'activation_token': 'activation_token_value', 'crypto_key_name': 'crypto_key_name_value', 'satisfies_pzs': True} - # 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 = eventarc.CreateChannelRequest.meta.fields["channel"] - - 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["channel"].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["channel"][field])): - del request_init["channel"][field][i][subfield] - else: - del request_init["channel"][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 - response = client.create_channel(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_channel_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_channel") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_channel") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreateChannelRequest.pb(eventarc.CreateChannelRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreateChannelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_channel_rest_bad_request(request_type=eventarc.UpdateChannelRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'channel': {'name': 'projects/sample1/locations/sample2/channels/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 - client.update_channel(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateChannelRequest, - dict, -]) -def test_update_channel_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'channel': {'name': 'projects/sample1/locations/sample2/channels/sample3'}} - request_init["channel"] = {'name': 'projects/sample1/locations/sample2/channels/sample3', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'provider': 'provider_value', 'pubsub_topic': 'pubsub_topic_value', 'state': 1, 'activation_token': 'activation_token_value', 'crypto_key_name': 'crypto_key_name_value', 'satisfies_pzs': True} - # 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 = eventarc.UpdateChannelRequest.meta.fields["channel"] - - 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["channel"].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["channel"][field])): - del request_init["channel"][field][i][subfield] - else: - del request_init["channel"][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 - response = client.update_channel(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_update_channel_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_channel") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_channel") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateChannelRequest.pb(eventarc.UpdateChannelRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdateChannelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_channel_rest_bad_request(request_type=eventarc.DeleteChannelRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channels/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 - client.delete_channel(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteChannelRequest, - dict, -]) -def test_delete_channel_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channels/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 - response = client.delete_channel(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_channel_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_channel") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_channel") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeleteChannelRequest.pb(eventarc.DeleteChannelRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeleteChannelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_channel(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_provider_rest_bad_request(request_type=eventarc.GetProviderRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/providers/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 - client.get_provider(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetProviderRequest, - dict, -]) -def test_get_provider_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/providers/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 = discovery.Provider( - 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 = discovery.Provider.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 - response = client.get_provider(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, discovery.Provider) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_provider_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_provider") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_provider") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetProviderRequest.pb(eventarc.GetProviderRequest()) - 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 - return_value = discovery.Provider.to_json(discovery.Provider()) - req.return_value.content = return_value - - request = eventarc.GetProviderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = discovery.Provider() - - client.get_provider(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_providers_rest_bad_request(request_type=eventarc.ListProvidersRequest): - client = EventarcClient( - 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 - client.list_providers(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListProvidersRequest, - dict, -]) -def test_list_providers_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListProvidersResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListProvidersResponse.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 - response = client.list_providers(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProvidersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_providers_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_providers") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_providers") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListProvidersRequest.pb(eventarc.ListProvidersRequest()) - 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 - return_value = eventarc.ListProvidersResponse.to_json(eventarc.ListProvidersResponse()) - req.return_value.content = return_value - - request = eventarc.ListProvidersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListProvidersResponse() - - client.list_providers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_channel_connection_rest_bad_request(request_type=eventarc.GetChannelConnectionRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 - client.get_channel_connection(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetChannelConnectionRequest, - dict, -]) -def test_get_channel_connection_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 = channel_connection.ChannelConnection( - name='name_value', - uid='uid_value', - channel='channel_value', - activation_token='activation_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 = channel_connection.ChannelConnection.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 - response = client.get_channel_connection(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, channel_connection.ChannelConnection) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.channel == 'channel_value' - assert response.activation_token == 'activation_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_channel_connection_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_channel_connection") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_channel_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetChannelConnectionRequest.pb(eventarc.GetChannelConnectionRequest()) - 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 - return_value = channel_connection.ChannelConnection.to_json(channel_connection.ChannelConnection()) - req.return_value.content = return_value - - request = eventarc.GetChannelConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = channel_connection.ChannelConnection() - - client.get_channel_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_channel_connections_rest_bad_request(request_type=eventarc.ListChannelConnectionsRequest): - client = EventarcClient( - 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 - client.list_channel_connections(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListChannelConnectionsRequest, - dict, -]) -def test_list_channel_connections_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListChannelConnectionsResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListChannelConnectionsResponse.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 - response = client.list_channel_connections(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelConnectionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_channel_connections_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_channel_connections") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_channel_connections") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListChannelConnectionsRequest.pb(eventarc.ListChannelConnectionsRequest()) - 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 - return_value = eventarc.ListChannelConnectionsResponse.to_json(eventarc.ListChannelConnectionsResponse()) - req.return_value.content = return_value - - request = eventarc.ListChannelConnectionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListChannelConnectionsResponse() - - client.list_channel_connections(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_channel_connection_rest_bad_request(request_type=eventarc.CreateChannelConnectionRequest): - client = EventarcClient( - 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 - client.create_channel_connection(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreateChannelConnectionRequest, - dict, -]) -def test_create_channel_connection_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["channel_connection"] = {'name': 'name_value', 'uid': 'uid_value', 'channel': 'channel_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'activation_token': 'activation_token_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 = eventarc.CreateChannelConnectionRequest.meta.fields["channel_connection"] - - 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["channel_connection"].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["channel_connection"][field])): - del request_init["channel_connection"][field][i][subfield] - else: - del request_init["channel_connection"][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 - response = client.create_channel_connection(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_channel_connection_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_channel_connection") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_channel_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreateChannelConnectionRequest.pb(eventarc.CreateChannelConnectionRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreateChannelConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_channel_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_channel_connection_rest_bad_request(request_type=eventarc.DeleteChannelConnectionRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 - client.delete_channel_connection(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteChannelConnectionRequest, - dict, -]) -def test_delete_channel_connection_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/channelConnections/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 - response = client.delete_channel_connection(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_channel_connection_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_channel_connection") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_channel_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeleteChannelConnectionRequest.pb(eventarc.DeleteChannelConnectionRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeleteChannelConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_channel_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_google_channel_config_rest_bad_request(request_type=eventarc.GetGoogleChannelConfigRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/googleChannelConfig'} - 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 - client.get_google_channel_config(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetGoogleChannelConfigRequest, - dict, -]) -def test_get_google_channel_config_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/googleChannelConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_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 = google_channel_config.GoogleChannelConfig.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 - response = client.get_google_channel_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, google_channel_config.GoogleChannelConfig) - assert response.name == 'name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_google_channel_config_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_google_channel_config") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_google_channel_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetGoogleChannelConfigRequest.pb(eventarc.GetGoogleChannelConfigRequest()) - 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 - return_value = google_channel_config.GoogleChannelConfig.to_json(google_channel_config.GoogleChannelConfig()) - req.return_value.content = return_value - - request = eventarc.GetGoogleChannelConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = google_channel_config.GoogleChannelConfig() - - client.get_google_channel_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_google_channel_config_rest_bad_request(request_type=eventarc.UpdateGoogleChannelConfigRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'google_channel_config': {'name': 'projects/sample1/locations/sample2/googleChannelConfig'}} - 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 - client.update_google_channel_config(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateGoogleChannelConfigRequest, - dict, -]) -def test_update_google_channel_config_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'google_channel_config': {'name': 'projects/sample1/locations/sample2/googleChannelConfig'}} - request_init["google_channel_config"] = {'name': 'projects/sample1/locations/sample2/googleChannelConfig', 'update_time': {'seconds': 751, 'nanos': 543}, 'crypto_key_name': 'crypto_key_name_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 = eventarc.UpdateGoogleChannelConfigRequest.meta.fields["google_channel_config"] - - 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["google_channel_config"].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["google_channel_config"][field])): - del request_init["google_channel_config"][field][i][subfield] - else: - del request_init["google_channel_config"][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 = gce_google_channel_config.GoogleChannelConfig( - name='name_value', - crypto_key_name='crypto_key_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 = gce_google_channel_config.GoogleChannelConfig.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 - response = client.update_google_channel_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) - assert response.name == 'name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_google_channel_config_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_google_channel_config") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_google_channel_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateGoogleChannelConfigRequest.pb(eventarc.UpdateGoogleChannelConfigRequest()) - 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 - return_value = gce_google_channel_config.GoogleChannelConfig.to_json(gce_google_channel_config.GoogleChannelConfig()) - req.return_value.content = return_value - - request = eventarc.UpdateGoogleChannelConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gce_google_channel_config.GoogleChannelConfig() - - client.update_google_channel_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_message_bus_rest_bad_request(request_type=eventarc.GetMessageBusRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 - client.get_message_bus(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetMessageBusRequest, - dict, -]) -def test_get_message_bus_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 = message_bus.MessageBus( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - crypto_key_name='crypto_key_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 = message_bus.MessageBus.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 - response = client.get_message_bus(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, message_bus.MessageBus) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_message_bus_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_message_bus") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_message_bus") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetMessageBusRequest.pb(eventarc.GetMessageBusRequest()) - 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 - return_value = message_bus.MessageBus.to_json(message_bus.MessageBus()) - req.return_value.content = return_value - - request = eventarc.GetMessageBusRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = message_bus.MessageBus() - - client.get_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_message_buses_rest_bad_request(request_type=eventarc.ListMessageBusesRequest): - client = EventarcClient( - 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 - client.list_message_buses(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListMessageBusesRequest, - dict, -]) -def test_list_message_buses_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListMessageBusesResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListMessageBusesResponse.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 - response = client.list_message_buses(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessageBusesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_message_buses_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_message_buses") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_message_buses") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListMessageBusesRequest.pb(eventarc.ListMessageBusesRequest()) - 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 - return_value = eventarc.ListMessageBusesResponse.to_json(eventarc.ListMessageBusesResponse()) - req.return_value.content = return_value - - request = eventarc.ListMessageBusesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListMessageBusesResponse() - - client.list_message_buses(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_message_bus_enrollments_rest_bad_request(request_type=eventarc.ListMessageBusEnrollmentsRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/messageBuses/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 - client.list_message_bus_enrollments(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListMessageBusEnrollmentsRequest, - dict, -]) -def test_list_message_bus_enrollments_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/messageBuses/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 = eventarc.ListMessageBusEnrollmentsResponse( - enrollments=['enrollments_value'], - next_page_token='next_page_token_value', - 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 = eventarc.ListMessageBusEnrollmentsResponse.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 - response = client.list_message_bus_enrollments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessageBusEnrollmentsPager) - assert response.enrollments == ['enrollments_value'] - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_message_bus_enrollments_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_message_bus_enrollments") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_message_bus_enrollments") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListMessageBusEnrollmentsRequest.pb(eventarc.ListMessageBusEnrollmentsRequest()) - 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 - return_value = eventarc.ListMessageBusEnrollmentsResponse.to_json(eventarc.ListMessageBusEnrollmentsResponse()) - req.return_value.content = return_value - - request = eventarc.ListMessageBusEnrollmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListMessageBusEnrollmentsResponse() - - client.list_message_bus_enrollments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_message_bus_rest_bad_request(request_type=eventarc.CreateMessageBusRequest): - client = EventarcClient( - 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 - client.create_message_bus(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreateMessageBusRequest, - dict, -]) -def test_create_message_bus_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["message_bus"] = {'name': 'name_value', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.CreateMessageBusRequest.meta.fields["message_bus"] - - 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["message_bus"].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["message_bus"][field])): - del request_init["message_bus"][field][i][subfield] - else: - del request_init["message_bus"][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 - response = client.create_message_bus(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_message_bus_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_message_bus") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_message_bus") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreateMessageBusRequest.pb(eventarc.CreateMessageBusRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreateMessageBusRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_message_bus_rest_bad_request(request_type=eventarc.UpdateMessageBusRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'message_bus': {'name': 'projects/sample1/locations/sample2/messageBuses/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 - client.update_message_bus(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateMessageBusRequest, - dict, -]) -def test_update_message_bus_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'message_bus': {'name': 'projects/sample1/locations/sample2/messageBuses/sample3'}} - request_init["message_bus"] = {'name': 'projects/sample1/locations/sample2/messageBuses/sample3', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.UpdateMessageBusRequest.meta.fields["message_bus"] - - 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["message_bus"].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["message_bus"][field])): - del request_init["message_bus"][field][i][subfield] - else: - del request_init["message_bus"][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 - response = client.update_message_bus(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_update_message_bus_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_message_bus") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_message_bus") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateMessageBusRequest.pb(eventarc.UpdateMessageBusRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdateMessageBusRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_message_bus_rest_bad_request(request_type=eventarc.DeleteMessageBusRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 - client.delete_message_bus(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteMessageBusRequest, - dict, -]) -def test_delete_message_bus_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/messageBuses/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 - response = client.delete_message_bus(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_message_bus_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_message_bus") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_message_bus") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeleteMessageBusRequest.pb(eventarc.DeleteMessageBusRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeleteMessageBusRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_message_bus(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_enrollment_rest_bad_request(request_type=eventarc.GetEnrollmentRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 - client.get_enrollment(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetEnrollmentRequest, - dict, -]) -def test_get_enrollment_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 = enrollment.Enrollment( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - cel_match='cel_match_value', - message_bus='message_bus_value', - destination='destination_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 = enrollment.Enrollment.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 - response = client.get_enrollment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, enrollment.Enrollment) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.cel_match == 'cel_match_value' - assert response.message_bus == 'message_bus_value' - assert response.destination == 'destination_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_enrollment_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_enrollment") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_enrollment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetEnrollmentRequest.pb(eventarc.GetEnrollmentRequest()) - 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 - return_value = enrollment.Enrollment.to_json(enrollment.Enrollment()) - req.return_value.content = return_value - - request = eventarc.GetEnrollmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = enrollment.Enrollment() - - client.get_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_enrollments_rest_bad_request(request_type=eventarc.ListEnrollmentsRequest): - client = EventarcClient( - 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 - client.list_enrollments(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListEnrollmentsRequest, - dict, -]) -def test_list_enrollments_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListEnrollmentsResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListEnrollmentsResponse.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 - response = client.list_enrollments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnrollmentsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_enrollments_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_enrollments") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_enrollments") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListEnrollmentsRequest.pb(eventarc.ListEnrollmentsRequest()) - 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 - return_value = eventarc.ListEnrollmentsResponse.to_json(eventarc.ListEnrollmentsResponse()) - req.return_value.content = return_value - - request = eventarc.ListEnrollmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListEnrollmentsResponse() - - client.list_enrollments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_enrollment_rest_bad_request(request_type=eventarc.CreateEnrollmentRequest): - client = EventarcClient( - 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 - client.create_enrollment(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreateEnrollmentRequest, - dict, -]) -def test_create_enrollment_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["enrollment"] = {'name': 'name_value', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'cel_match': 'cel_match_value', 'message_bus': 'message_bus_value', 'destination': 'destination_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 = eventarc.CreateEnrollmentRequest.meta.fields["enrollment"] - - 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["enrollment"].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["enrollment"][field])): - del request_init["enrollment"][field][i][subfield] - else: - del request_init["enrollment"][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 - response = client.create_enrollment(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_enrollment_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_enrollment") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_enrollment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreateEnrollmentRequest.pb(eventarc.CreateEnrollmentRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreateEnrollmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_enrollment_rest_bad_request(request_type=eventarc.UpdateEnrollmentRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'enrollment': {'name': 'projects/sample1/locations/sample2/enrollments/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 - client.update_enrollment(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateEnrollmentRequest, - dict, -]) -def test_update_enrollment_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'enrollment': {'name': 'projects/sample1/locations/sample2/enrollments/sample3'}} - request_init["enrollment"] = {'name': 'projects/sample1/locations/sample2/enrollments/sample3', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'cel_match': 'cel_match_value', 'message_bus': 'message_bus_value', 'destination': 'destination_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 = eventarc.UpdateEnrollmentRequest.meta.fields["enrollment"] - - 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["enrollment"].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["enrollment"][field])): - del request_init["enrollment"][field][i][subfield] - else: - del request_init["enrollment"][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 - response = client.update_enrollment(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_update_enrollment_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_enrollment") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_enrollment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateEnrollmentRequest.pb(eventarc.UpdateEnrollmentRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdateEnrollmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_enrollment_rest_bad_request(request_type=eventarc.DeleteEnrollmentRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 - client.delete_enrollment(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteEnrollmentRequest, - dict, -]) -def test_delete_enrollment_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/enrollments/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 - response = client.delete_enrollment(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_enrollment_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_enrollment") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_enrollment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeleteEnrollmentRequest.pb(eventarc.DeleteEnrollmentRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeleteEnrollmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_enrollment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_pipeline_rest_bad_request(request_type=eventarc.GetPipelineRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 - client.get_pipeline(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetPipelineRequest, - dict, -]) -def test_get_pipeline_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 = pipeline.Pipeline( - name='name_value', - uid='uid_value', - display_name='display_name_value', - crypto_key_name='crypto_key_name_value', - 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 = pipeline.Pipeline.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 - response = client.get_pipeline(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pipeline.Pipeline) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.display_name == 'display_name_value' - assert response.crypto_key_name == 'crypto_key_name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_pipeline_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_pipeline") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_pipeline") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetPipelineRequest.pb(eventarc.GetPipelineRequest()) - 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 - return_value = pipeline.Pipeline.to_json(pipeline.Pipeline()) - req.return_value.content = return_value - - request = eventarc.GetPipelineRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pipeline.Pipeline() - - client.get_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_pipelines_rest_bad_request(request_type=eventarc.ListPipelinesRequest): - client = EventarcClient( - 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 - client.list_pipelines(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListPipelinesRequest, - dict, -]) -def test_list_pipelines_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListPipelinesResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListPipelinesResponse.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 - response = client.list_pipelines(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPipelinesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_pipelines_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_pipelines") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_pipelines") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListPipelinesRequest.pb(eventarc.ListPipelinesRequest()) - 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 - return_value = eventarc.ListPipelinesResponse.to_json(eventarc.ListPipelinesResponse()) - req.return_value.content = return_value - - request = eventarc.ListPipelinesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListPipelinesResponse() - - client.list_pipelines(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_pipeline_rest_bad_request(request_type=eventarc.CreatePipelineRequest): - client = EventarcClient( - 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 - client.create_pipeline(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreatePipelineRequest, - dict, -]) -def test_create_pipeline_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["pipeline"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'uid': 'uid_value', 'annotations': {}, 'display_name': 'display_name_value', 'destinations': [{'network_config': {'network_attachment': 'network_attachment_value'}, 'http_endpoint': {'uri': 'uri_value', 'message_binding_template': 'message_binding_template_value'}, 'workflow': 'workflow_value', 'message_bus': 'message_bus_value', 'topic': 'topic_value', 'authentication_config': {'google_oidc': {'service_account': 'service_account_value', 'audience': 'audience_value'}, 'oauth_token': {'service_account': 'service_account_value', 'scope': 'scope_value'}}, 'output_payload_format': {'protobuf': {'schema_definition': 'schema_definition_value'}, 'avro': {'schema_definition': 'schema_definition_value'}, 'json': {}}}], 'mediations': [{'transformation': {'transformation_template': 'transformation_template_value'}}], 'crypto_key_name': 'crypto_key_name_value', 'input_payload_format': {}, 'logging_config': {'log_severity': 1}, 'retry_policy': {'max_attempts': 1303, 'min_retry_delay': {'seconds': 751, 'nanos': 543}, 'max_retry_delay': {}}, '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 = eventarc.CreatePipelineRequest.meta.fields["pipeline"] - - 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["pipeline"].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["pipeline"][field])): - del request_init["pipeline"][field][i][subfield] - else: - del request_init["pipeline"][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 - response = client.create_pipeline(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_pipeline_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_pipeline") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_pipeline") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreatePipelineRequest.pb(eventarc.CreatePipelineRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreatePipelineRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_pipeline_rest_bad_request(request_type=eventarc.UpdatePipelineRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'pipeline': {'name': 'projects/sample1/locations/sample2/pipelines/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 - client.update_pipeline(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdatePipelineRequest, - dict, -]) -def test_update_pipeline_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'pipeline': {'name': 'projects/sample1/locations/sample2/pipelines/sample3'}} - request_init["pipeline"] = {'name': 'projects/sample1/locations/sample2/pipelines/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'uid': 'uid_value', 'annotations': {}, 'display_name': 'display_name_value', 'destinations': [{'network_config': {'network_attachment': 'network_attachment_value'}, 'http_endpoint': {'uri': 'uri_value', 'message_binding_template': 'message_binding_template_value'}, 'workflow': 'workflow_value', 'message_bus': 'message_bus_value', 'topic': 'topic_value', 'authentication_config': {'google_oidc': {'service_account': 'service_account_value', 'audience': 'audience_value'}, 'oauth_token': {'service_account': 'service_account_value', 'scope': 'scope_value'}}, 'output_payload_format': {'protobuf': {'schema_definition': 'schema_definition_value'}, 'avro': {'schema_definition': 'schema_definition_value'}, 'json': {}}}], 'mediations': [{'transformation': {'transformation_template': 'transformation_template_value'}}], 'crypto_key_name': 'crypto_key_name_value', 'input_payload_format': {}, 'logging_config': {'log_severity': 1}, 'retry_policy': {'max_attempts': 1303, 'min_retry_delay': {'seconds': 751, 'nanos': 543}, 'max_retry_delay': {}}, '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 = eventarc.UpdatePipelineRequest.meta.fields["pipeline"] - - 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["pipeline"].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["pipeline"][field])): - del request_init["pipeline"][field][i][subfield] - else: - del request_init["pipeline"][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 - response = client.update_pipeline(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_update_pipeline_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_pipeline") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_pipeline") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdatePipelineRequest.pb(eventarc.UpdatePipelineRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdatePipelineRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_pipeline_rest_bad_request(request_type=eventarc.DeletePipelineRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 - client.delete_pipeline(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeletePipelineRequest, - dict, -]) -def test_delete_pipeline_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/pipelines/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 - response = client.delete_pipeline(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_pipeline_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_pipeline") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_pipeline") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeletePipelineRequest.pb(eventarc.DeletePipelineRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeletePipelineRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_pipeline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_google_api_source_rest_bad_request(request_type=eventarc.GetGoogleApiSourceRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 - client.get_google_api_source(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.GetGoogleApiSourceRequest, - dict, -]) -def test_get_google_api_source_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 = google_api_source.GoogleApiSource( - name='name_value', - uid='uid_value', - etag='etag_value', - display_name='display_name_value', - destination='destination_value', - crypto_key_name='crypto_key_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 = google_api_source.GoogleApiSource.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 - response = client.get_google_api_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, google_api_source.GoogleApiSource) - assert response.name == 'name_value' - assert response.uid == 'uid_value' - assert response.etag == 'etag_value' - assert response.display_name == 'display_name_value' - assert response.destination == 'destination_value' - assert response.crypto_key_name == 'crypto_key_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_google_api_source_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_google_api_source") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_get_google_api_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetGoogleApiSourceRequest.pb(eventarc.GetGoogleApiSourceRequest()) - 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 - return_value = google_api_source.GoogleApiSource.to_json(google_api_source.GoogleApiSource()) - req.return_value.content = return_value - - request = eventarc.GetGoogleApiSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = google_api_source.GoogleApiSource() - - client.get_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_google_api_sources_rest_bad_request(request_type=eventarc.ListGoogleApiSourcesRequest): - client = EventarcClient( - 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 - client.list_google_api_sources(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.ListGoogleApiSourcesRequest, - dict, -]) -def test_list_google_api_sources_rest_call_success(request_type): - client = EventarcClient( - 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 = eventarc.ListGoogleApiSourcesResponse( - next_page_token='next_page_token_value', - 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 = eventarc.ListGoogleApiSourcesResponse.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 - response = client.list_google_api_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGoogleApiSourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_google_api_sources_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_list_google_api_sources") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_list_google_api_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.ListGoogleApiSourcesRequest.pb(eventarc.ListGoogleApiSourcesRequest()) - 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 - return_value = eventarc.ListGoogleApiSourcesResponse.to_json(eventarc.ListGoogleApiSourcesResponse()) - req.return_value.content = return_value - - request = eventarc.ListGoogleApiSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = eventarc.ListGoogleApiSourcesResponse() - - client.list_google_api_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_google_api_source_rest_bad_request(request_type=eventarc.CreateGoogleApiSourceRequest): - client = EventarcClient( - 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 - client.create_google_api_source(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.CreateGoogleApiSourceRequest, - dict, -]) -def test_create_google_api_source_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["google_api_source"] = {'name': 'name_value', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'destination': 'destination_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.CreateGoogleApiSourceRequest.meta.fields["google_api_source"] - - 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["google_api_source"].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["google_api_source"][field])): - del request_init["google_api_source"][field][i][subfield] - else: - del request_init["google_api_source"][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 - response = client.create_google_api_source(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_google_api_source_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_create_google_api_source") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_create_google_api_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.CreateGoogleApiSourceRequest.pb(eventarc.CreateGoogleApiSourceRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.CreateGoogleApiSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_google_api_source_rest_bad_request(request_type=eventarc.UpdateGoogleApiSourceRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'google_api_source': {'name': 'projects/sample1/locations/sample2/googleApiSources/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 - client.update_google_api_source(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.UpdateGoogleApiSourceRequest, - dict, -]) -def test_update_google_api_source_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'google_api_source': {'name': 'projects/sample1/locations/sample2/googleApiSources/sample3'}} - request_init["google_api_source"] = {'name': 'projects/sample1/locations/sample2/googleApiSources/sample3', 'uid': 'uid_value', 'etag': 'etag_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'annotations': {}, 'display_name': 'display_name_value', 'destination': 'destination_value', 'crypto_key_name': 'crypto_key_name_value', 'logging_config': {'log_severity': 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 = eventarc.UpdateGoogleApiSourceRequest.meta.fields["google_api_source"] - - 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["google_api_source"].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["google_api_source"][field])): - del request_init["google_api_source"][field][i][subfield] - else: - del request_init["google_api_source"][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 - response = client.update_google_api_source(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_update_google_api_source_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_google_api_source") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_update_google_api_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateGoogleApiSourceRequest.pb(eventarc.UpdateGoogleApiSourceRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdateGoogleApiSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_google_api_source_rest_bad_request(request_type=eventarc.DeleteGoogleApiSourceRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 - client.delete_google_api_source(request) - - -@pytest.mark.parametrize("request_type", [ - eventarc.DeleteGoogleApiSourceRequest, - dict, -]) -def test_delete_google_api_source_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/googleApiSources/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 - response = client.delete_google_api_source(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_google_api_source_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_delete_google_api_source") as post, \ - mock.patch.object(transports.EventarcRestInterceptor, "pre_delete_google_api_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.DeleteGoogleApiSourceRequest.pb(eventarc.DeleteGoogleApiSourceRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.DeleteGoogleApiSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_google_api_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = EventarcClient( - 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 - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EventarcClient( - 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 - - 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 = EventarcClient( - 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 - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EventarcClient( - 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 - - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/triggers/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 - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/triggers/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 - - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/triggers/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 - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/triggers/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 - - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/triggers/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 - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/triggers/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 - - 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_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = EventarcClient( - 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 - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EventarcClient( - 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 - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = EventarcClient( - 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 - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = EventarcClient( - 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 - - 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 = EventarcClient( - 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 - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EventarcClient( - 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 - - 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 = EventarcClient( - 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 - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EventarcClient( - 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 - - 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 = EventarcClient( - 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_get_trigger_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trigger), - '__call__') as call: - client.get_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetTriggerRequest() - - 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_triggers_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_triggers), - '__call__') as call: - client.list_triggers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListTriggersRequest() - - 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_trigger_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trigger), - '__call__') as call: - client.create_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateTriggerRequest() - - 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_trigger_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trigger), - '__call__') as call: - client.update_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateTriggerRequest() - - 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_trigger_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_trigger), - '__call__') as call: - client.delete_trigger(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteTriggerRequest() - - 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_channel_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel), - '__call__') as call: - client.get_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelRequest() - - 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_channels_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channels), - '__call__') as call: - client.list_channels(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelsRequest() - - 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_channel_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_), - '__call__') as call: - client.create_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelRequest() - - 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_channel_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_channel), - '__call__') as call: - client.update_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateChannelRequest() - - 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_channel_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel), - '__call__') as call: - client.delete_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelRequest() - - 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_provider_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_provider), - '__call__') as call: - client.get_provider(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetProviderRequest() - - 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_providers_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_providers), - '__call__') as call: - client.list_providers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListProvidersRequest() - - 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_channel_connection_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), - '__call__') as call: - client.get_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelConnectionRequest() - - 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_channel_connections_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), - '__call__') as call: - client.list_channel_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelConnectionsRequest() - - 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_channel_connection_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), - '__call__') as call: - client.create_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelConnectionRequest() - - 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_channel_connection_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), - '__call__') as call: - client.delete_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelConnectionRequest() - - 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_google_channel_config_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), - '__call__') as call: - client.get_google_channel_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleChannelConfigRequest() - - 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_google_channel_config_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), - '__call__') as call: - client.update_google_channel_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleChannelConfigRequest() - - 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_message_bus_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_message_bus), - '__call__') as call: - client.get_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetMessageBusRequest() - - 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_message_buses_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_message_buses), - '__call__') as call: - client.list_message_buses(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListMessageBusesRequest() - - 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_message_bus_enrollments_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_message_bus_enrollments), - '__call__') as call: - client.list_message_bus_enrollments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListMessageBusEnrollmentsRequest() - - 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_message_bus_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_message_bus), - '__call__') as call: - client.create_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateMessageBusRequest() - - 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_message_bus_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_message_bus), - '__call__') as call: - client.update_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateMessageBusRequest() - - 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_message_bus_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_message_bus), - '__call__') as call: - client.delete_message_bus(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteMessageBusRequest() - - 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_enrollment_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_enrollment), - '__call__') as call: - client.get_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetEnrollmentRequest() - - 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_enrollments_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_enrollments), - '__call__') as call: - client.list_enrollments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListEnrollmentsRequest() - - 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_enrollment_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_enrollment), - '__call__') as call: - client.create_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateEnrollmentRequest() - - 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_enrollment_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_enrollment), - '__call__') as call: - client.update_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateEnrollmentRequest() - - 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_enrollment_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_enrollment), - '__call__') as call: - client.delete_enrollment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteEnrollmentRequest() - - 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_pipeline_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_pipeline), - '__call__') as call: - client.get_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetPipelineRequest() - - 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_pipelines_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_pipelines), - '__call__') as call: - client.list_pipelines(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListPipelinesRequest() - - 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_pipeline_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_pipeline), - '__call__') as call: - client.create_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreatePipelineRequest() - - 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_pipeline_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_pipeline), - '__call__') as call: - client.update_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdatePipelineRequest() - - 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_pipeline_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_pipeline), - '__call__') as call: - client.delete_pipeline(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeletePipelineRequest() - - 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_google_api_source_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_api_source), - '__call__') as call: - client.get_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleApiSourceRequest() - - 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_google_api_sources_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_google_api_sources), - '__call__') as call: - client.list_google_api_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListGoogleApiSourcesRequest() - - 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_google_api_source_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_google_api_source), - '__call__') as call: - client.create_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateGoogleApiSourceRequest() - - 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_google_api_source_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_api_source), - '__call__') as call: - client.update_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleApiSourceRequest() - - 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_google_api_source_empty_call_rest(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_google_api_source), - '__call__') as call: - client.delete_google_api_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteGoogleApiSourceRequest() - - assert args[0] == request_msg - - -def test_eventarc_rest_lro_client(): - client = EventarcClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EventarcGrpcTransport, - ) - -def test_eventarc_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EventarcTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_eventarc_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.eventarc_v1.services.eventarc.transports.EventarcTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EventarcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_trigger', - 'list_triggers', - 'create_trigger', - 'update_trigger', - 'delete_trigger', - 'get_channel', - 'list_channels', - 'create_channel_', - 'update_channel', - 'delete_channel', - 'get_provider', - 'list_providers', - 'get_channel_connection', - 'list_channel_connections', - 'create_channel_connection', - 'delete_channel_connection', - 'get_google_channel_config', - 'update_google_channel_config', - 'get_message_bus', - 'list_message_buses', - 'list_message_bus_enrollments', - 'create_message_bus', - 'update_message_bus', - 'delete_message_bus', - 'get_enrollment', - 'list_enrollments', - 'create_enrollment', - 'update_enrollment', - 'delete_enrollment', - 'get_pipeline', - 'list_pipelines', - 'create_pipeline', - 'update_pipeline', - 'delete_pipeline', - 'get_google_api_source', - 'list_google_api_sources', - 'create_google_api_source', - 'update_google_api_source', - 'delete_google_api_source', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_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_eventarc_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.eventarc_v1.services.eventarc.transports.EventarcTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EventarcTransport( - 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_eventarc_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.eventarc_v1.services.eventarc.transports.EventarcTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EventarcTransport() - adc.assert_called_once() - - -def test_eventarc_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) - EventarcClient() - 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.EventarcGrpcTransport, - transports.EventarcGrpcAsyncIOTransport, - ], -) -def test_eventarc_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.EventarcGrpcTransport, - transports.EventarcGrpcAsyncIOTransport, - transports.EventarcRestTransport, - ], -) -def test_eventarc_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.EventarcGrpcTransport, grpc_helpers), - (transports.EventarcGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_eventarc_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( - "eventarc.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="eventarc.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EventarcGrpcTransport, transports.EventarcGrpcAsyncIOTransport]) -def test_eventarc_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_eventarc_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.EventarcRestTransport ( - 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_eventarc_host_no_port(transport_name): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='eventarc.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'eventarc.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://eventarc.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_eventarc_host_with_port(transport_name): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='eventarc.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'eventarc.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://eventarc.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_eventarc_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EventarcClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EventarcClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_trigger._session - session2 = client2.transport.get_trigger._session - assert session1 != session2 - session1 = client1.transport.list_triggers._session - session2 = client2.transport.list_triggers._session - assert session1 != session2 - session1 = client1.transport.create_trigger._session - session2 = client2.transport.create_trigger._session - assert session1 != session2 - session1 = client1.transport.update_trigger._session - session2 = client2.transport.update_trigger._session - assert session1 != session2 - session1 = client1.transport.delete_trigger._session - session2 = client2.transport.delete_trigger._session - assert session1 != session2 - session1 = client1.transport.get_channel._session - session2 = client2.transport.get_channel._session - assert session1 != session2 - session1 = client1.transport.list_channels._session - session2 = client2.transport.list_channels._session - assert session1 != session2 - session1 = client1.transport.create_channel_._session - session2 = client2.transport.create_channel_._session - assert session1 != session2 - session1 = client1.transport.update_channel._session - session2 = client2.transport.update_channel._session - assert session1 != session2 - session1 = client1.transport.delete_channel._session - session2 = client2.transport.delete_channel._session - assert session1 != session2 - session1 = client1.transport.get_provider._session - session2 = client2.transport.get_provider._session - assert session1 != session2 - session1 = client1.transport.list_providers._session - session2 = client2.transport.list_providers._session - assert session1 != session2 - session1 = client1.transport.get_channel_connection._session - session2 = client2.transport.get_channel_connection._session - assert session1 != session2 - session1 = client1.transport.list_channel_connections._session - session2 = client2.transport.list_channel_connections._session - assert session1 != session2 - session1 = client1.transport.create_channel_connection._session - session2 = client2.transport.create_channel_connection._session - assert session1 != session2 - session1 = client1.transport.delete_channel_connection._session - session2 = client2.transport.delete_channel_connection._session - assert session1 != session2 - session1 = client1.transport.get_google_channel_config._session - session2 = client2.transport.get_google_channel_config._session - assert session1 != session2 - session1 = client1.transport.update_google_channel_config._session - session2 = client2.transport.update_google_channel_config._session - assert session1 != session2 - session1 = client1.transport.get_message_bus._session - session2 = client2.transport.get_message_bus._session - assert session1 != session2 - session1 = client1.transport.list_message_buses._session - session2 = client2.transport.list_message_buses._session - assert session1 != session2 - session1 = client1.transport.list_message_bus_enrollments._session - session2 = client2.transport.list_message_bus_enrollments._session - assert session1 != session2 - session1 = client1.transport.create_message_bus._session - session2 = client2.transport.create_message_bus._session - assert session1 != session2 - session1 = client1.transport.update_message_bus._session - session2 = client2.transport.update_message_bus._session - assert session1 != session2 - session1 = client1.transport.delete_message_bus._session - session2 = client2.transport.delete_message_bus._session - assert session1 != session2 - session1 = client1.transport.get_enrollment._session - session2 = client2.transport.get_enrollment._session - assert session1 != session2 - session1 = client1.transport.list_enrollments._session - session2 = client2.transport.list_enrollments._session - assert session1 != session2 - session1 = client1.transport.create_enrollment._session - session2 = client2.transport.create_enrollment._session - assert session1 != session2 - session1 = client1.transport.update_enrollment._session - session2 = client2.transport.update_enrollment._session - assert session1 != session2 - session1 = client1.transport.delete_enrollment._session - session2 = client2.transport.delete_enrollment._session - assert session1 != session2 - session1 = client1.transport.get_pipeline._session - session2 = client2.transport.get_pipeline._session - assert session1 != session2 - session1 = client1.transport.list_pipelines._session - session2 = client2.transport.list_pipelines._session - assert session1 != session2 - session1 = client1.transport.create_pipeline._session - session2 = client2.transport.create_pipeline._session - assert session1 != session2 - session1 = client1.transport.update_pipeline._session - session2 = client2.transport.update_pipeline._session - assert session1 != session2 - session1 = client1.transport.delete_pipeline._session - session2 = client2.transport.delete_pipeline._session - assert session1 != session2 - session1 = client1.transport.get_google_api_source._session - session2 = client2.transport.get_google_api_source._session - assert session1 != session2 - session1 = client1.transport.list_google_api_sources._session - session2 = client2.transport.list_google_api_sources._session - assert session1 != session2 - session1 = client1.transport.create_google_api_source._session - session2 = client2.transport.create_google_api_source._session - assert session1 != session2 - session1 = client1.transport.update_google_api_source._session - session2 = client2.transport.update_google_api_source._session - assert session1 != session2 - session1 = client1.transport.delete_google_api_source._session - session2 = client2.transport.delete_google_api_source._session - assert session1 != session2 -def test_eventarc_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EventarcGrpcTransport( - 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_eventarc_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EventarcGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EventarcGrpcTransport, transports.EventarcGrpcAsyncIOTransport]) -def test_eventarc_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.EventarcGrpcTransport, transports.EventarcGrpcAsyncIOTransport]) -def test_eventarc_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_eventarc_grpc_lro_client(): - client = EventarcClient( - 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_eventarc_grpc_lro_async_client(): - client = EventarcAsyncClient( - 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_channel_path(): - project = "squid" - location = "clam" - channel = "whelk" - expected = "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) - actual = EventarcClient.channel_path(project, location, channel) - assert expected == actual - - -def test_parse_channel_path(): - expected = { - "project": "octopus", - "location": "oyster", - "channel": "nudibranch", - } - path = EventarcClient.channel_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_channel_path(path) - assert expected == actual - -def test_channel_connection_path(): - project = "cuttlefish" - location = "mussel" - channel_connection = "winkle" - expected = "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) - actual = EventarcClient.channel_connection_path(project, location, channel_connection) - assert expected == actual - - -def test_parse_channel_connection_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "channel_connection": "abalone", - } - path = EventarcClient.channel_connection_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_channel_connection_path(path) - assert expected == actual - -def test_cloud_function_path(): - project = "squid" - location = "clam" - function = "whelk" - expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - actual = EventarcClient.cloud_function_path(project, location, function) - assert expected == actual - - -def test_parse_cloud_function_path(): - expected = { - "project": "octopus", - "location": "oyster", - "function": "nudibranch", - } - path = EventarcClient.cloud_function_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_cloud_function_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 = EventarcClient.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 = EventarcClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_crypto_key_path(path) - assert expected == actual - -def test_enrollment_path(): - project = "whelk" - location = "octopus" - enrollment = "oyster" - expected = "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) - actual = EventarcClient.enrollment_path(project, location, enrollment) - assert expected == actual - - -def test_parse_enrollment_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "enrollment": "mussel", - } - path = EventarcClient.enrollment_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_enrollment_path(path) - assert expected == actual - -def test_google_api_source_path(): - project = "winkle" - location = "nautilus" - google_api_source = "scallop" - expected = "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) - actual = EventarcClient.google_api_source_path(project, location, google_api_source) - assert expected == actual - - -def test_parse_google_api_source_path(): - expected = { - "project": "abalone", - "location": "squid", - "google_api_source": "clam", - } - path = EventarcClient.google_api_source_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_google_api_source_path(path) - assert expected == actual - -def test_google_channel_config_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) - actual = EventarcClient.google_channel_config_path(project, location) - assert expected == actual - - -def test_parse_google_channel_config_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = EventarcClient.google_channel_config_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_google_channel_config_path(path) - assert expected == actual - -def test_message_bus_path(): - project = "cuttlefish" - location = "mussel" - message_bus = "winkle" - expected = "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) - actual = EventarcClient.message_bus_path(project, location, message_bus) - assert expected == actual - - -def test_parse_message_bus_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "message_bus": "abalone", - } - path = EventarcClient.message_bus_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_message_bus_path(path) - assert expected == actual - -def test_network_attachment_path(): - project = "squid" - region = "clam" - networkattachment = "whelk" - expected = "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) - actual = EventarcClient.network_attachment_path(project, region, networkattachment) - assert expected == actual - - -def test_parse_network_attachment_path(): - expected = { - "project": "octopus", - "region": "oyster", - "networkattachment": "nudibranch", - } - path = EventarcClient.network_attachment_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_network_attachment_path(path) - assert expected == actual - -def test_pipeline_path(): - project = "cuttlefish" - location = "mussel" - pipeline = "winkle" - expected = "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) - actual = EventarcClient.pipeline_path(project, location, pipeline) - assert expected == actual - - -def test_parse_pipeline_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "pipeline": "abalone", - } - path = EventarcClient.pipeline_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_pipeline_path(path) - assert expected == actual - -def test_provider_path(): - project = "squid" - location = "clam" - provider = "whelk" - expected = "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) - actual = EventarcClient.provider_path(project, location, provider) - assert expected == actual - - -def test_parse_provider_path(): - expected = { - "project": "octopus", - "location": "oyster", - "provider": "nudibranch", - } - path = EventarcClient.provider_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_provider_path(path) - assert expected == actual - -def test_service_path(): - expected = "*".format() - actual = EventarcClient.service_path() - assert expected == actual - - -def test_parse_service_path(): - expected = { - } - path = EventarcClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_service_path(path) - assert expected == actual - -def test_service_account_path(): - project = "cuttlefish" - service_account = "mussel" - expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) - actual = EventarcClient.service_account_path(project, service_account) - assert expected == actual - - -def test_parse_service_account_path(): - expected = { - "project": "winkle", - "service_account": "nautilus", - } - path = EventarcClient.service_account_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_service_account_path(path) - assert expected == actual - -def test_topic_path(): - project = "scallop" - topic = "abalone" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = EventarcClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "squid", - "topic": "clam", - } - path = EventarcClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_topic_path(path) - assert expected == actual - -def test_trigger_path(): - project = "whelk" - location = "octopus" - trigger = "oyster" - expected = "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) - actual = EventarcClient.trigger_path(project, location, trigger) - assert expected == actual - - -def test_parse_trigger_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "trigger": "mussel", - } - path = EventarcClient.trigger_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_trigger_path(path) - assert expected == actual - -def test_workflow_path(): - project = "winkle" - location = "nautilus" - workflow = "scallop" - expected = "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) - actual = EventarcClient.workflow_path(project, location, workflow) - assert expected == actual - - -def test_parse_workflow_path(): - expected = { - "project": "abalone", - "location": "squid", - "workflow": "clam", - } - path = EventarcClient.workflow_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_workflow_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EventarcClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = EventarcClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = EventarcClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = EventarcClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EventarcClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = EventarcClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = EventarcClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = EventarcClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.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 = EventarcClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = EventarcClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EventarcClient.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.EventarcTransport, '_prep_wrapped_messages') as prep: - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EventarcTransport, '_prep_wrapped_messages') as prep: - transport_class = EventarcClient.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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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_cancel_operation(transport: str = "grpc"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EventarcAsyncClient( - 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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcAsyncClient( - 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 = EventarcClient( - 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 = EventarcClient( - 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", [ - (EventarcClient, transports.EventarcGrpcTransport), - (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport), -]) -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-eventarc/google/cloud/eventarc/gapic_version.py b/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py index 0b9427f4e8a5..558c8aab67c5 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py index 0b9427f4e8a5..558c8aab67c5 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py index edc5f4c09175..7078508682e1 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py @@ -29,7 +29,7 @@ class LoggingConfig(proto.Message): r"""The configuration for Platform Telemetry logging for Eventarc - Avdvanced resources. + Advanced resources. Attributes: log_severity (google.cloud.eventarc_v1.types.LoggingConfig.LogSeverity): diff --git a/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json b/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json index a678125bd8ef..c94a230c3122 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json +++ b/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-eventarc", - "version": "1.13.1" + "version": "0.1.0" }, "snippets": [ {