From 5e89b3d845dd9275e58decb18ff52dbc0472572d Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 21 Jul 2026 16:31:30 +0000 Subject: [PATCH 1/5] feat(generator): delegate REST transcoding to google-api-core --- packages/gapic-generator/api-common-protos | 1 + .../gapic/generator/generator.py | 2 +- .../%name_%version/%sub/_compat.py.j2 | 96 + .../%sub/services/%service/_shared_macros.j2 | 21 +- .../transports/_rest_mixins_base.py.j2 | 22 +- .../services/%service/transports/rest.py.j2 | 5 +- .../%service/transports/rest_asyncio.py.j2 | 5 +- .../%service/transports/rest_base.py.j2 | 43 - .../generated_showcase/.coveragerc | 13 + .../generated_showcase/.flake8 | 34 + .../generated_showcase/LICENSE | 202 + .../generated_showcase/MANIFEST.in | 20 + .../generated_showcase/README.rst | 143 + .../docs/_static/custom.css | 20 + .../docs/_templates/layout.html | 50 + .../generated_showcase/docs/conf.py | 417 + .../generated_showcase/docs/index.rst | 10 + .../docs/multiprocessing.rst | 7 + .../docs/showcase_v1beta1/echo.rst | 10 + .../docs/showcase_v1beta1/identity.rst | 10 + .../docs/showcase_v1beta1/messaging.rst | 10 + .../docs/showcase_v1beta1/services_.rst | 8 + .../docs/showcase_v1beta1/types_.rst | 6 + .../google/showcase/__init__.py | 127 + .../google/showcase/gapic_version.py | 16 + .../google/showcase/py.typed | 2 + .../google/showcase_v1beta1/__init__.py | 223 + .../google/showcase_v1beta1/_compat.py | 108 + .../google/showcase_v1beta1/gapic_version.py | 16 + .../google/showcase_v1beta1/py.typed | 2 + .../showcase_v1beta1/services/__init__.py | 15 + .../services/echo/__init__.py | 22 + .../services/echo/async_client.py | 1937 +++ .../showcase_v1beta1/services/echo/client.py | 2361 +++ .../showcase_v1beta1/services/echo/pagers.py | 450 + .../services/echo/transports/README.rst | 10 + .../services/echo/transports/__init__.py | 38 + .../services/echo/transports/base.py | 455 + .../services/echo/transports/grpc.py | 831 ++ .../services/echo/transports/grpc_asyncio.py | 972 ++ .../services/echo/transports/rest.py | 2975 ++++ .../services/echo/transports/rest_base.py | 412 + .../services/identity/__init__.py | 22 + .../services/identity/async_client.py | 1441 ++ .../services/identity/client.py | 1872 +++ .../services/identity/pagers.py | 166 + .../services/identity/transports/README.rst | 10 + .../services/identity/transports/__init__.py | 38 + .../services/identity/transports/base.py | 370 + .../services/identity/transports/grpc.py | 649 + .../identity/transports/grpc_asyncio.py | 755 + .../services/identity/transports/rest.py | 2270 +++ .../services/identity/transports/rest_base.py | 354 + .../services/messaging/__init__.py | 22 + .../services/messaging/async_client.py | 2367 +++ .../services/messaging/client.py | 2811 ++++ .../services/messaging/pagers.py | 305 + .../services/messaging/transports/README.rst | 10 + .../services/messaging/transports/__init__.py | 38 + .../services/messaging/transports/base.py | 542 + .../services/messaging/transports/grpc.py | 917 ++ .../messaging/transports/grpc_asyncio.py | 1108 ++ .../services/messaging/transports/rest.py | 3559 +++++ .../messaging/transports/rest_base.py | 524 + .../google/showcase_v1beta1/types/__init__.py | 116 + .../google/showcase_v1beta1/types/echo.py | 591 + .../google/showcase_v1beta1/types/identity.py | 255 + .../showcase_v1beta1/types/messaging.py | 668 + .../generated_showcase/noxfile.py | 635 + ...7469_v1beta1_generated_echo_block_async.py | 51 + ...:7469_v1beta1_generated_echo_block_sync.py | 51 + ...:7469_v1beta1_generated_echo_chat_async.py | 63 + ...t:7469_v1beta1_generated_echo_chat_sync.py | 63 + ...69_v1beta1_generated_echo_collect_async.py | 62 + ...469_v1beta1_generated_echo_collect_sync.py | 62 + ...:7469_v1beta1_generated_echo_echo_async.py | 52 + ...generated_echo_echo_error_details_async.py | 51 + ..._generated_echo_echo_error_details_sync.py | 51 + ...t:7469_v1beta1_generated_echo_echo_sync.py | 52 + ...469_v1beta1_generated_echo_expand_async.py | 52 + ...7469_v1beta1_generated_echo_expand_sync.py | 52 + ...beta1_generated_echo_paged_expand_async.py | 53 + ...enerated_echo_paged_expand_legacy_async.py | 53 + ...d_echo_paged_expand_legacy_mapped_async.py | 53 + ...ed_echo_paged_expand_legacy_mapped_sync.py | 53 + ...generated_echo_paged_expand_legacy_sync.py | 53 + ...1beta1_generated_echo_paged_expand_sync.py | 53 + ...:7469_v1beta1_generated_echo_wait_async.py | 55 + ...t:7469_v1beta1_generated_echo_wait_sync.py | 55 + ...a1_generated_identity_create_user_async.py | 51 + ...ta1_generated_identity_create_user_sync.py | 51 + ...a1_generated_identity_delete_user_async.py | 50 + ...ta1_generated_identity_delete_user_sync.py | 50 + ...beta1_generated_identity_get_user_async.py | 52 + ...1beta1_generated_identity_get_user_sync.py | 52 + ...ta1_generated_identity_list_users_async.py | 52 + ...eta1_generated_identity_list_users_sync.py | 52 + ...a1_generated_identity_update_user_async.py | 51 + ...ta1_generated_identity_update_user_sync.py | 51 + ...beta1_generated_messaging_connect_async.py | 62 + ...1beta1_generated_messaging_connect_sync.py | 62 + ..._generated_messaging_create_blurb_async.py | 52 + ...1_generated_messaging_create_blurb_sync.py | 52 + ...1_generated_messaging_create_room_async.py | 51 + ...a1_generated_messaging_create_room_sync.py | 51 + ..._generated_messaging_delete_blurb_async.py | 50 + ...1_generated_messaging_delete_blurb_sync.py | 50 + ...1_generated_messaging_delete_room_async.py | 50 + ...a1_generated_messaging_delete_room_sync.py | 50 + ...ta1_generated_messaging_get_blurb_async.py | 52 + ...eta1_generated_messaging_get_blurb_sync.py | 52 + ...eta1_generated_messaging_get_room_async.py | 52 + ...beta1_generated_messaging_get_room_sync.py | 52 + ...1_generated_messaging_list_blurbs_async.py | 53 + ...a1_generated_messaging_list_blurbs_sync.py | 53 + ...a1_generated_messaging_list_rooms_async.py | 52 + ...ta1_generated_messaging_list_rooms_sync.py | 52 + ...generated_messaging_search_blurbs_async.py | 56 + ..._generated_messaging_search_blurbs_sync.py | 56 + ...1_generated_messaging_send_blurbs_async.py | 62 + ...a1_generated_messaging_send_blurbs_sync.py | 62 + ...generated_messaging_stream_blurbs_async.py | 53 + ..._generated_messaging_stream_blurbs_sync.py | 53 + ..._generated_messaging_update_blurb_async.py | 51 + ...1_generated_messaging_update_blurb_sync.py | 51 + ...1_generated_messaging_update_room_async.py | 51 + ...a1_generated_messaging_update_room_sync.py | 51 + ...ppet_metadata_google.showcase.v1beta1.json | 4618 ++++++ .../generated_showcase/setup.py | 101 + .../generated_showcase/showcase.desc | Bin 0 -> 260515 bytes .../showcase_grpc_service_config.json | 90 + .../generated_showcase/showcase_v1beta1.yaml | 91 + .../testing/constraints-3.10.txt | 12 + .../testing/constraints-3.11.txt | 11 + .../testing/constraints-3.12.txt | 11 + .../testing/constraints-3.13.txt | 13 + .../testing/constraints-3.14.txt | 13 + .../testing/constraints-3.15.txt | 13 + .../generated_showcase/tests/__init__.py | 16 + .../generated_showcase/tests/unit/__init__.py | 16 + .../tests/unit/gapic/__init__.py | 16 + .../unit/gapic/showcase_v1beta1/__init__.py | 16 + .../unit/gapic/showcase_v1beta1/test_echo.py | 9408 ++++++++++++ .../gapic/showcase_v1beta1/test_identity.py | 6950 +++++++++ .../gapic/showcase_v1beta1/test_messaging.py | 11873 ++++++++++++++++ packages/gapic-generator/noxfile.py | 9 + 146 files changed, 70836 insertions(+), 79 deletions(-) create mode 160000 packages/gapic-generator/api-common-protos create mode 100644 packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 create mode 100644 packages/gapic-generator/generated_showcase/.coveragerc create mode 100644 packages/gapic-generator/generated_showcase/.flake8 create mode 100644 packages/gapic-generator/generated_showcase/LICENSE create mode 100644 packages/gapic-generator/generated_showcase/MANIFEST.in create mode 100644 packages/gapic-generator/generated_showcase/README.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/_static/custom.css create mode 100644 packages/gapic-generator/generated_showcase/docs/_templates/layout.html create mode 100644 packages/gapic-generator/generated_showcase/docs/conf.py create mode 100644 packages/gapic-generator/generated_showcase/docs/index.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/multiprocessing.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst create mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst create mode 100644 packages/gapic-generator/generated_showcase/google/showcase/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase/py.typed create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py create mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py create mode 100644 packages/gapic-generator/generated_showcase/noxfile.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py create mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json create mode 100644 packages/gapic-generator/generated_showcase/setup.py create mode 100644 packages/gapic-generator/generated_showcase/showcase.desc create mode 100644 packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json create mode 100644 packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml create mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt create mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt create mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt create mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt create mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt create mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt create mode 100644 packages/gapic-generator/generated_showcase/tests/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/tests/unit/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py create mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py create mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py create mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py diff --git a/packages/gapic-generator/api-common-protos b/packages/gapic-generator/api-common-protos new file mode 160000 index 000000000000..3332dec52775 --- /dev/null +++ b/packages/gapic-generator/api-common-protos @@ -0,0 +1 @@ +Subproject commit 3332dec527759859840a3a2ff108c67a54708130 diff --git a/packages/gapic-generator/gapic/generator/generator.py b/packages/gapic-generator/gapic/generator/generator.py index 9fe56aa9de1d..c1932abbe426 100644 --- a/packages/gapic-generator/gapic/generator/generator.py +++ b/packages/gapic-generator/gapic/generator/generator.py @@ -120,7 +120,7 @@ def get_response(self, api_schema: api.API, opts: Options) -> CodeGeneratorRespo for template_name in client_templates: # Quick check: Skip "private" templates. filename = template_name.split("/")[-1] - if filename.startswith("_") and filename != "__init__.py.j2": + if filename.startswith("_") and filename not in ("__init__.py.j2", "_compat.py.j2"): continue # Append to the output files dictionary. diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 new file mode 100644 index 000000000000..753dd6026676 --- /dev/null +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -0,0 +1,96 @@ +# {% include '_license.j2' %} + +from typing import Any, Dict, List, Optional, Tuple + +try: + from google.api_core.rest_helpers import ( + flatten_query_params, + transcode_request, + ) +except ImportError: # pragma: NO COVER + # TODO: Remove these fallbacks when google-api-core >= 2.18.0 is the minimum required version. + import functools + import json + import operator + from google.protobuf import json_format # type: ignore + from google.api_core import path_template # type: ignore + + def flatten_query_params(obj, strict=False): # pragma: NO COVER + if obj is not None and not isinstance(obj, dict): + raise TypeError("flatten_query_params must be called with dict object") + return _flatten(obj, key_path=[], strict=strict) + + def _flatten(obj, key_path, strict=False): # pragma: NO COVER + if obj is None: + return [] + if isinstance(obj, dict): + return _flatten_dict(obj, key_path=key_path, strict=strict) + if isinstance(obj, list): + return _flatten_list(obj, key_path=key_path, strict=strict) + return _flatten_value(obj, key_path=key_path, strict=strict) + + def _is_primitive_value(obj): # pragma: NO COVER + if obj is None: + return False + if isinstance(obj, (list, dict)): + raise ValueError("query params may not contain repeated dicts or lists") + return True + + def _flatten_value(obj, key_path, strict=False): # pragma: NO COVER + return [(".".join(key_path), _canonicalize(obj, strict=strict))] + + def _flatten_dict(obj, key_path, strict=False): # pragma: NO COVER + items = ( + _flatten(value, key_path=key_path + [key], strict=strict) + for key, value in obj.items() + ) + return functools.reduce(operator.concat, items, []) + + def _flatten_list(elems, key_path, strict=False): # pragma: NO COVER + items = ( + _flatten_value(elem, key_path=key_path, strict=strict) + for elem in elems + if _is_primitive_value(elem) + ) + return functools.reduce(operator.concat, items, []) + + def _canonicalize(obj, strict=False): # pragma: NO COVER + if strict: + value = str(obj) + if isinstance(obj, bool): + value = value.lower() + return value + return obj + + def transcode_request( # pragma: NO COVER + http_options: List[Dict[str, str]], + request: Any, + required_fields_default_values: Optional[Dict[str, Any]] = None, + rest_numeric_enums: bool = False, + ) -> Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: + pb_request = getattr(request, "_pb", request) + transcoded_request = path_template.transcode(http_options, pb_request) + + body_json = None + if transcoded_request.get("body") is not None: + body_json = json_format.MessageToJson( + transcoded_request["body"], + use_integers_for_enums=rest_numeric_enums, + ) + + query_params_json = {} + if transcoded_request.get("query_params") is not None: + query_params_json = json.loads(json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=rest_numeric_enums, + )) + + if required_fields_default_values: + for k, v in required_fields_default_values.items(): + if k not in query_params_json: + query_params_json[k] = v + + if rest_numeric_enums: + query_params_json["$alt"] = "json;enum-encoding=int" + + return transcoded_request, body_json, query_params_json diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 index 755e4530e7ba..6e58759112ca 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 @@ -198,22 +198,23 @@ def _get_http_options(): service: The service. is_async (bool): Used to determine the code path i.e. whether for sync or async call. is_request_message_proto_plus_type (bool): Used to determine whether the request message is a proto-plus type. #} -{% macro rest_call_method_common(body_spec, method_name, service, is_async=False, is_request_message_proto_plus_type=False) %} +{% macro rest_call_method_common(body_spec, method_name, service, is_async=False, is_request_message_proto_plus_type=False, rest_numeric_enums=False) %} {% set service_name = service.name %} {% set await_prefix = "await " if is_async else "" %} {% set async_class_prefix = "Async" if is_async else "" %} http_options = _Base{{ service_name }}RestTransport._Base{{method_name}}._get_http_options() - {# TODO(https://github.com/googleapis/gapic-generator-python/issues/2274): Add debug log before intercepting a request #} request, metadata = {{ await_prefix }}self._interceptor.pre_{{ method_name|snake_case }}(request, metadata) - transcoded_request = _Base{{ service_name }}RestTransport._Base{{method_name}}._get_transcoded_request(http_options, request) - - {% if body_spec %} - body = _Base{{ service_name }}RestTransport._Base{{method_name}}._get_request_body_json(transcoded_request) - {% endif %}{# body_spec #} - - # Jsonify the query params - query_params = _Base{{ service_name }}RestTransport._Base{{method_name}}._get_query_params_json(transcoded_request) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _Base{{ service_name }}RestTransport._Base{{method_name}}, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums={{ rest_numeric_enums }}, + ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/_rest_mixins_base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/_rest_mixins_base.py.j2 index 16cc77ea937c..f768500d5755 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/_rest_mixins_base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/_rest_mixins_base.py.j2 @@ -25,27 +25,7 @@ {{ shared_macros.http_options_method(api.mixin_http_options["{}".format(name)])|indent(8)}} - @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 - - {% set body_spec = api.mixin_http_options["{}".format(name)][0].body %} - {%- if body_spec %} - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - - {%- endif %} {# body_spec #} - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params + pass {% endfor %} {% endif %} {# rest in opts.transport #} diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest.py.j2 index 49c1374053b5..a3e08a447d06 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest.py.j2 @@ -10,7 +10,8 @@ from google.auth.transport.requests import AuthorizedSession # 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 +{% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %} +from {{package_path}} import _compat as rest_helpers from google.api_core import rest_streaming from google.api_core import gapic_v1 import google.protobuf @@ -245,7 +246,7 @@ class {{service.name}}RestTransport(_Base{{ service.name }}RestTransport): {% endif %} """ - {{ shared_macros.rest_call_method_common(body_spec, method.name, service, False, method.input.ident.is_proto_plus_type)|indent(8) }} + {{ shared_macros.rest_call_method_common(body_spec, method.name, service, False, method.input.ident.is_proto_plus_type, opts.rest_numeric_enums)|indent(8) }} {% if not method.void %} # Return the response diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_asyncio.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_asyncio.py.j2 index 80980572c30a..83c8cd28b986 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_asyncio.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_asyncio.py.j2 @@ -32,7 +32,8 @@ from google.iam.v1 import policy_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore {% endif %} from google.api_core import retry_async as retries -from google.api_core import rest_helpers +{% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %} +from {{package_path}} import _compat as rest_helpers from google.api_core import rest_streaming_async # type: ignore import google.protobuf @@ -203,7 +204,7 @@ class Async{{service.name}}RestTransport(_Base{{ service.name }}RestTransport): {% endif %} """ - {{ shared_macros.rest_call_method_common(body_spec, method.name, service, True, method.input.ident.is_proto_plus_type)|indent(8) }} + {{ shared_macros.rest_call_method_common(body_spec, method.name, service, True, method.input.ident.is_proto_plus_type, opts.rest_numeric_enums)|indent(8) }} {% if not method.void %} # Return the response diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_base.py.j2 index b79785afc517..90c0e10d6403 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/rest_base.py.j2 @@ -120,51 +120,8 @@ class _Base{{ service.name }}RestTransport({{service.name}}Transport): def _get_unset_required_fields(cls, message_dict): return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} {% endif %}{# required fields #} - {% set method_http_options = method.http_options %} - {{ shared_macros.http_options_method(method_http_options)|indent(8) }} - - @staticmethod - def _get_transcoded_request(http_options, request): - {% if method.input.ident.is_proto_plus_type %} - pb_request = {{method.input.ident}}.pb(request) - {% else %} - pb_request = request - {% endif %} - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - {% set body_spec = method.http_options[0].body %} - {%- if body_spec %} - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums={{ opts.rest_numeric_enums }} - ) - return body - - {%- endif %}{# body_spec #} - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums={{ opts.rest_numeric_enums }}, - )) - {% if method.input.required_fields %} - query_params.update(_Base{{ service.name }}RestTransport._Base{{method.name}}._get_unset_required_fields(query_params)) - {% endif %}{# required fields #} - - {% if opts.rest_numeric_enums %} - query_params["$alt"] = "json;enum-encoding=int" - {% endif %} - return query_params - {% endif %}{# method.http_options and not method.client_streaming #} {% endfor %} diff --git a/packages/gapic-generator/generated_showcase/.coveragerc b/packages/gapic-generator/generated_showcase/.coveragerc new file mode 100644 index 000000000000..55f3b8c4ec27 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/showcase/__init__.py + google/showcase/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/packages/gapic-generator/generated_showcase/.flake8 b/packages/gapic-generator/generated_showcase/.flake8 new file mode 100644 index 000000000000..f9069a84687b --- /dev/null +++ b/packages/gapic-generator/generated_showcase/.flake8 @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/packages/gapic-generator/generated_showcase/LICENSE b/packages/gapic-generator/generated_showcase/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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/packages/gapic-generator/generated_showcase/MANIFEST.in b/packages/gapic-generator/generated_showcase/MANIFEST.in new file mode 100644 index 000000000000..f932577add9d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/packages/gapic-generator/generated_showcase/README.rst b/packages/gapic-generator/generated_showcase/README.rst new file mode 100644 index 000000000000..4e6b807730d9 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Showcase 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 Showcase 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 + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/packages/gapic-generator/generated_showcase/docs/_static/custom.css b/packages/gapic-generator/generated_showcase/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/packages/gapic-generator/generated_showcase/docs/_templates/layout.html b/packages/gapic-generator/generated_showcase/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/packages/gapic-generator/generated_showcase/docs/conf.py b/packages/gapic-generator/generated_showcase/docs/conf.py new file mode 100644 index 000000000000..1b373c50bdd8 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/conf.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-showcase 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 logging +import os +import shlex +import sys +import logging +from typing import Any + +# 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("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# 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.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +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-showcase" +copyright = u"2026, Google, LLC" +author = u"Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# 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 Client Libraries for google-showcase", + "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-showcase-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-showcase.tex", + u"google-showcase 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-showcase", + "google-showcase 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-showcase", + "google-showcase Documentation", + author, + "google-showcase", + "google-showcase Library", + "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": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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 + +# Setup for sphinx behaviors such as warning filters. +class UnexpectedUnindentFilter(logging.Filter): + """Filter out warnings about unexpected unindentation following bullet lists.""" + + def filter(self, record: logging.LogRecord) -> bool: + """Filter the log record. + + Args: + record (logging.LogRecord): The log record. + + Returns: + bool: False to suppress the warning, True to allow it. + """ + msg = record.getMessage() + if "Bullet list ends without a blank line" in msg: + return False + return True + + +def setup(app: Any) -> None: + """Setup the Sphinx application. + + Args: + app (Any): The Sphinx application. + """ + # Sphinx's logger is hierarchical. Adding a filter to the + # root 'sphinx' logger will catch warnings from all sub-loggers. + logger = logging.getLogger('sphinx') + logger.addFilter(UnexpectedUnindentFilter()) diff --git a/packages/gapic-generator/generated_showcase/docs/index.rst b/packages/gapic-generator/generated_showcase/docs/index.rst new file mode 100644 index 000000000000..272113be4cd4 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + showcase_v1beta1/services_ + showcase_v1beta1/types_ diff --git a/packages/gapic-generator/generated_showcase/docs/multiprocessing.rst b/packages/gapic-generator/generated_showcase/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst new file mode 100644 index 000000000000..654e25afb43e --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst @@ -0,0 +1,10 @@ +Echo +---------------------- + +.. automodule:: google.showcase_v1beta1.services.echo + :members: + :inherited-members: + +.. automodule:: google.showcase_v1beta1.services.echo.pagers + :members: + :inherited-members: diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst new file mode 100644 index 000000000000..37affa6718e6 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst @@ -0,0 +1,10 @@ +Identity +-------------------------- + +.. automodule:: google.showcase_v1beta1.services.identity + :members: + :inherited-members: + +.. automodule:: google.showcase_v1beta1.services.identity.pagers + :members: + :inherited-members: diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst new file mode 100644 index 000000000000..34ee90be489d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst @@ -0,0 +1,10 @@ +Messaging +--------------------------- + +.. automodule:: google.showcase_v1beta1.services.messaging + :members: + :inherited-members: + +.. automodule:: google.showcase_v1beta1.services.messaging.pagers + :members: + :inherited-members: diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst new file mode 100644 index 000000000000..348915d7ea57 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst @@ -0,0 +1,8 @@ +Services for Google Showcase v1beta1 API +======================================== +.. toctree:: + :maxdepth: 2 + + echo + identity + messaging diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst new file mode 100644 index 000000000000..ad3d8ea4fe27 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Showcase v1beta1 API +===================================== + +.. automodule:: google.showcase_v1beta1.types + :members: + :show-inheritance: diff --git a/packages/gapic-generator/generated_showcase/google/showcase/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase/__init__.py new file mode 100644 index 000000000000..13c5d82c9928 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase/__init__.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.showcase_v1beta1.services.echo.client import EchoClient +from google.showcase_v1beta1.services.echo.async_client import EchoAsyncClient +from google.showcase_v1beta1.services.identity.client import IdentityClient +from google.showcase_v1beta1.services.identity.async_client import IdentityAsyncClient +from google.showcase_v1beta1.services.messaging.client import MessagingClient +from google.showcase_v1beta1.services.messaging.async_client import MessagingAsyncClient + +from google.showcase_v1beta1.types.echo import BlockRequest +from google.showcase_v1beta1.types.echo import BlockResponse +from google.showcase_v1beta1.types.echo import EchoErrorDetailsRequest +from google.showcase_v1beta1.types.echo import EchoErrorDetailsResponse +from google.showcase_v1beta1.types.echo import EchoRequest +from google.showcase_v1beta1.types.echo import EchoResponse +from google.showcase_v1beta1.types.echo import ErrorWithMultipleDetails +from google.showcase_v1beta1.types.echo import ErrorWithSingleDetail +from google.showcase_v1beta1.types.echo import ExpandRequest +from google.showcase_v1beta1.types.echo import PagedExpandLegacyMappedResponse +from google.showcase_v1beta1.types.echo import PagedExpandLegacyRequest +from google.showcase_v1beta1.types.echo import PagedExpandRequest +from google.showcase_v1beta1.types.echo import PagedExpandResponse +from google.showcase_v1beta1.types.echo import PagedExpandResponseList +from google.showcase_v1beta1.types.echo import WaitMetadata +from google.showcase_v1beta1.types.echo import WaitRequest +from google.showcase_v1beta1.types.echo import WaitResponse +from google.showcase_v1beta1.types.echo import Severity +from google.showcase_v1beta1.types.identity import CreateUserRequest +from google.showcase_v1beta1.types.identity import DeleteUserRequest +from google.showcase_v1beta1.types.identity import GetUserRequest +from google.showcase_v1beta1.types.identity import ListUsersRequest +from google.showcase_v1beta1.types.identity import ListUsersResponse +from google.showcase_v1beta1.types.identity import UpdateUserRequest +from google.showcase_v1beta1.types.identity import User +from google.showcase_v1beta1.types.messaging import Blurb +from google.showcase_v1beta1.types.messaging import ConnectRequest +from google.showcase_v1beta1.types.messaging import CreateBlurbRequest +from google.showcase_v1beta1.types.messaging import CreateRoomRequest +from google.showcase_v1beta1.types.messaging import DeleteBlurbRequest +from google.showcase_v1beta1.types.messaging import DeleteRoomRequest +from google.showcase_v1beta1.types.messaging import GetBlurbRequest +from google.showcase_v1beta1.types.messaging import GetRoomRequest +from google.showcase_v1beta1.types.messaging import ListBlurbsRequest +from google.showcase_v1beta1.types.messaging import ListBlurbsResponse +from google.showcase_v1beta1.types.messaging import ListRoomsRequest +from google.showcase_v1beta1.types.messaging import ListRoomsResponse +from google.showcase_v1beta1.types.messaging import Room +from google.showcase_v1beta1.types.messaging import SearchBlurbsMetadata +from google.showcase_v1beta1.types.messaging import SearchBlurbsRequest +from google.showcase_v1beta1.types.messaging import SearchBlurbsResponse +from google.showcase_v1beta1.types.messaging import SendBlurbsResponse +from google.showcase_v1beta1.types.messaging import StreamBlurbsRequest +from google.showcase_v1beta1.types.messaging import StreamBlurbsResponse +from google.showcase_v1beta1.types.messaging import UpdateBlurbRequest +from google.showcase_v1beta1.types.messaging import UpdateRoomRequest + +__all__ = ('EchoClient', + 'EchoAsyncClient', + 'IdentityClient', + 'IdentityAsyncClient', + 'MessagingClient', + 'MessagingAsyncClient', + 'BlockRequest', + 'BlockResponse', + 'EchoErrorDetailsRequest', + 'EchoErrorDetailsResponse', + 'EchoRequest', + 'EchoResponse', + 'ErrorWithMultipleDetails', + 'ErrorWithSingleDetail', + 'ExpandRequest', + 'PagedExpandLegacyMappedResponse', + 'PagedExpandLegacyRequest', + 'PagedExpandRequest', + 'PagedExpandResponse', + 'PagedExpandResponseList', + 'WaitMetadata', + 'WaitRequest', + 'WaitResponse', + 'Severity', + 'CreateUserRequest', + 'DeleteUserRequest', + 'GetUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + 'UpdateUserRequest', + 'User', + 'Blurb', + 'ConnectRequest', + 'CreateBlurbRequest', + 'CreateRoomRequest', + 'DeleteBlurbRequest', + 'DeleteRoomRequest', + 'GetBlurbRequest', + 'GetRoomRequest', + 'ListBlurbsRequest', + 'ListBlurbsResponse', + 'ListRoomsRequest', + 'ListRoomsResponse', + 'Room', + 'SearchBlurbsMetadata', + 'SearchBlurbsRequest', + 'SearchBlurbsResponse', + 'SendBlurbsResponse', + 'StreamBlurbsRequest', + 'StreamBlurbsResponse', + 'UpdateBlurbRequest', + 'UpdateRoomRequest', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py b/packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py new file mode 100644 index 000000000000..e89a0031d71b --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/google/showcase/py.typed b/packages/gapic-generator/generated_showcase/google/showcase/py.typed new file mode 100644 index 000000000000..22eee9858aaf --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-showcase package uses inline types. diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py new file mode 100644 index 000000000000..47ab3dc442fb --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1 import gapic_version as package_version + +import google.api_core as api_core +import sys + +__version__ = package_version.__version__ + +from importlib import metadata + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__ = { +"google.showcase_v1beta1.services.echo", +"google.showcase_v1beta1.services.identity", +"google.showcase_v1beta1.services.messaging", +"google.showcase_v1beta1.types.echo", +"google.showcase_v1beta1.types.identity", +"google.showcase_v1beta1.types.messaging", +} + + +from .services.echo import EchoClient +from .services.echo import EchoAsyncClient +from .services.identity import IdentityClient +from .services.identity import IdentityAsyncClient +from .services.messaging import MessagingClient +from .services.messaging import MessagingAsyncClient + +from .types.echo import BlockRequest +from .types.echo import BlockResponse +from .types.echo import EchoErrorDetailsRequest +from .types.echo import EchoErrorDetailsResponse +from .types.echo import EchoRequest +from .types.echo import EchoResponse +from .types.echo import ErrorWithMultipleDetails +from .types.echo import ErrorWithSingleDetail +from .types.echo import ExpandRequest +from .types.echo import PagedExpandLegacyMappedResponse +from .types.echo import PagedExpandLegacyRequest +from .types.echo import PagedExpandRequest +from .types.echo import PagedExpandResponse +from .types.echo import PagedExpandResponseList +from .types.echo import WaitMetadata +from .types.echo import WaitRequest +from .types.echo import WaitResponse +from .types.echo import Severity +from .types.identity import CreateUserRequest +from .types.identity import DeleteUserRequest +from .types.identity import GetUserRequest +from .types.identity import ListUsersRequest +from .types.identity import ListUsersResponse +from .types.identity import UpdateUserRequest +from .types.identity import User +from .types.messaging import Blurb +from .types.messaging import ConnectRequest +from .types.messaging import CreateBlurbRequest +from .types.messaging import CreateRoomRequest +from .types.messaging import DeleteBlurbRequest +from .types.messaging import DeleteRoomRequest +from .types.messaging import GetBlurbRequest +from .types.messaging import GetRoomRequest +from .types.messaging import ListBlurbsRequest +from .types.messaging import ListBlurbsResponse +from .types.messaging import ListRoomsRequest +from .types.messaging import ListRoomsResponse +from .types.messaging import Room +from .types.messaging import SearchBlurbsMetadata +from .types.messaging import SearchBlurbsRequest +from .types.messaging import SearchBlurbsResponse +from .types.messaging import SendBlurbsResponse +from .types.messaging import StreamBlurbsRequest +from .types.messaging import StreamBlurbsResponse +from .types.messaging import UpdateBlurbRequest +from .types.messaging import UpdateRoomRequest + +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.showcase_v1beta1") # type: ignore + api_core.check_dependency_versions("google.showcase_v1beta1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.showcase_v1beta1" + if sys.version_info < (3, 10): + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "6.33.5" -> (6, 33, 5) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "6.33.5" + _next_supported_version_tuple = (6, 33, 5) + _recommendation = " (we recommend 7.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) + except Exception: + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") + +__all__ = ( + 'EchoAsyncClient', + 'IdentityAsyncClient', + 'MessagingAsyncClient', +'BlockRequest', +'BlockResponse', +'Blurb', +'ConnectRequest', +'CreateBlurbRequest', +'CreateRoomRequest', +'CreateUserRequest', +'DeleteBlurbRequest', +'DeleteRoomRequest', +'DeleteUserRequest', +'EchoClient', +'EchoErrorDetailsRequest', +'EchoErrorDetailsResponse', +'EchoRequest', +'EchoResponse', +'ErrorWithMultipleDetails', +'ErrorWithSingleDetail', +'ExpandRequest', +'GetBlurbRequest', +'GetRoomRequest', +'GetUserRequest', +'IdentityClient', +'ListBlurbsRequest', +'ListBlurbsResponse', +'ListRoomsRequest', +'ListRoomsResponse', +'ListUsersRequest', +'ListUsersResponse', +'MessagingClient', +'PagedExpandLegacyMappedResponse', +'PagedExpandLegacyRequest', +'PagedExpandRequest', +'PagedExpandResponse', +'PagedExpandResponseList', +'Room', +'SearchBlurbsMetadata', +'SearchBlurbsRequest', +'SearchBlurbsResponse', +'SendBlurbsResponse', +'Severity', +'StreamBlurbsRequest', +'StreamBlurbsResponse', +'UpdateBlurbRequest', +'UpdateRoomRequest', +'UpdateUserRequest', +'User', +'WaitMetadata', +'WaitRequest', +'WaitResponse', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py new file mode 100644 index 000000000000..dd6a5824d373 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py @@ -0,0 +1,108 @@ +# # Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, Dict, List, Optional, Tuple + +try: + from google.api_core.rest_helpers import ( + flatten_query_params, + transcode_request, + ) +except ImportError: # pragma: NO COVER + # TODO: Remove these fallbacks when google-api-core >= 2.18.0 is the minimum required version. + import functools + import json + import operator + from google.protobuf import json_format # type: ignore + from google.api_core import path_template # type: ignore + + def flatten_query_params(obj, strict=False): # pragma: NO COVER + if obj is not None and not isinstance(obj, dict): + raise TypeError("flatten_query_params must be called with dict object") + return _flatten(obj, key_path=[], strict=strict) + + def _flatten(obj, key_path, strict=False): # pragma: NO COVER + if obj is None: + return [] + if isinstance(obj, dict): + return _flatten_dict(obj, key_path=key_path, strict=strict) + if isinstance(obj, list): + return _flatten_list(obj, key_path=key_path, strict=strict) + return _flatten_value(obj, key_path=key_path, strict=strict) + + def _is_primitive_value(obj): # pragma: NO COVER + if obj is None: + return False + if isinstance(obj, (list, dict)): + raise ValueError("query params may not contain repeated dicts or lists") + return True + + def _flatten_value(obj, key_path, strict=False): # pragma: NO COVER + return [(".".join(key_path), _canonicalize(obj, strict=strict))] + + def _flatten_dict(obj, key_path, strict=False): # pragma: NO COVER + items = ( + _flatten(value, key_path=key_path + [key], strict=strict) + for key, value in obj.items() + ) + return functools.reduce(operator.concat, items, []) + + def _flatten_list(elems, key_path, strict=False): # pragma: NO COVER + items = ( + _flatten_value(elem, key_path=key_path, strict=strict) + for elem in elems + if _is_primitive_value(elem) + ) + return functools.reduce(operator.concat, items, []) + + def _canonicalize(obj, strict=False): # pragma: NO COVER + if strict: + value = str(obj) + if isinstance(obj, bool): + value = value.lower() + return value + return obj + + def transcode_request( # pragma: NO COVER + http_options: List[Dict[str, str]], + request: Any, + required_fields_default_values: Optional[Dict[str, Any]] = None, + rest_numeric_enums: bool = False, + ) -> Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: + pb_request = getattr(request, "_pb", request) + transcoded_request = path_template.transcode(http_options, pb_request) + + body_json = None + if transcoded_request.get("body") is not None: + body_json = json_format.MessageToJson( + transcoded_request["body"], + use_integers_for_enums=rest_numeric_enums, + ) + + query_params_json = {} + if transcoded_request.get("query_params") is not None: + query_params_json = json.loads(json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=rest_numeric_enums, + )) + + if required_fields_default_values: + for k, v in required_fields_default_values.items(): + if k not in query_params_json: + query_params_json[k] = v + + if rest_numeric_enums: + query_params_json["$alt"] = "json;enum-encoding=int" + + return transcoded_request, body_json, query_params_json diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py new file mode 100644 index 000000000000..e89a0031d71b --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed new file mode 100644 index 000000000000..22eee9858aaf --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-showcase package uses inline types. diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py new file mode 100644 index 000000000000..e5b65be3966a --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 EchoClient +from .async_client import EchoAsyncClient + +__all__ = ( + 'EchoClient', + 'EchoAsyncClient', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py new file mode 100644 index 000000000000..5ddcca846a9f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py @@ -0,0 +1,1937 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import uuid + +from google.showcase_v1beta1 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 +import google.protobuf + +try: + from google.api_core import version_header + HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + HAS_GOOGLE_API_CORE_VERSION_HEADER = False + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.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.showcase_v1beta1.services.echo import pagers +from google.showcase_v1beta1.types import echo as gs_echo +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from .transports.base import EchoTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EchoGrpcAsyncIOTransport +from .client import EchoClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class EchoAsyncClient: + """This service is used showcase the four main types of rpcs - + unary, server side streaming, client side streaming, and + bidirectional streaming. This service also exposes methods that + explicitly implement server delay, and paginated calls. Set the + 'showcase-trailer' metadata key on any method to have the values + echoed in the response trailers. Set the 'x-goog-request-params' + metadata key on any method to have the values echoed in the + response headers. + This class implements API version v1_20240408.""" + + _client: EchoClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EchoClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EchoClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EchoClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EchoClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(EchoClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EchoClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EchoClient.common_folder_path) + parse_common_folder_path = staticmethod(EchoClient.parse_common_folder_path) + common_organization_path = staticmethod(EchoClient.common_organization_path) + parse_common_organization_path = staticmethod(EchoClient.parse_common_organization_path) + common_project_path = staticmethod(EchoClient.common_project_path) + parse_common_project_path = staticmethod(EchoClient.parse_common_project_path) + common_location_path = staticmethod(EchoClient.common_location_path) + parse_common_location_path = staticmethod(EchoClient.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: + EchoAsyncClient: The constructed client. + """ + sa_info_func = ( + EchoClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(EchoAsyncClient, info, *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: + EchoAsyncClient: The constructed client. + """ + sa_file_func = ( + EchoClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(EchoAsyncClient, filename, *args, **kwargs) + + 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 EchoClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EchoTransport: + """Returns the transport used by the client instance. + + Returns: + EchoTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = EchoClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EchoTransport, Callable[..., EchoTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the echo 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,EchoTransport,Callable[..., EchoTransport]]]): + 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 EchoTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = EchoClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.showcase_v1beta1.EchoAsyncClient`.", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.showcase.v1beta1.Echo", + "credentialsType": None, + } + ) + + async def echo(self, + request: Optional[Union[gs_echo.EchoRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.EchoResponse: + r"""This method simply echoes the request. This method + showcases unary RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_echo(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # Make the request + response = await client.echo(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.EchoRequest, dict]]): + The request object. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.EchoResponse: + The response message for the Echo + methods. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.EchoRequest): + request = gs_echo.EchoRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.echo] + + header_params = {} + + if request.header: + header_params["header"] = request.header + + routing_param_regex = re.compile('^(?P.*)$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("routing_id"): + header_params["routing_id"] = regex_match.group("routing_id") + + routing_param_regex = re.compile('^(?Pregions/[^/]+/zones/[^/]+(?:/.*)?)$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("table_name"): + header_params["table_name"] = regex_match.group("table_name") + + routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("super_id"): + header_params["super_id"] = regex_match.group("super_id") + + routing_param_regex = re.compile('^(?Pprojects/[^/]+/instances/[^/]+(?:/.*)?)$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("table_name"): + header_params["table_name"] = regex_match.group("table_name") + + routing_param_regex = re.compile('^projects/[^/]+/(?Pinstances/[^/]+)(?:/.*)?$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("instance_id"): + header_params["instance_id"] = regex_match.group("instance_id") + + routing_param_regex = re.compile('^(?P.*)$') + regex_match = routing_param_regex.match(request.other_header) + if regex_match and regex_match.group("baz"): + header_params["baz"] = regex_match.group("baz") + + routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') + regex_match = routing_param_regex.match(request.other_header) + if regex_match and regex_match.group("qux"): + header_params["qux"] = regex_match.group("qux") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + self._client._setup_request_id(request, 'request_id', False) + self._client._setup_request_id(request, 'other_request_id', True) + + # 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 echo_error_details(self, + request: Optional[Union[gs_echo.EchoErrorDetailsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.EchoErrorDetailsResponse: + r"""This method returns error details in a repeated + "google.protobuf.Any" field. This method showcases handling + errors thus encoded, particularly over REST transport. Note that + GAPICs only allow the type "google.protobuf.Any" for field paths + ending in "error.details", and, at run-time, the actual types + for these fields must be one of the types in + google/rpc/error_details.proto. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_echo_error_details(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoErrorDetailsRequest( + ) + + # Make the request + response = await client.echo_error_details(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.EchoErrorDetailsRequest, dict]]): + The request object. The request message used for the + EchoErrorDetails method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.EchoErrorDetailsResponse: + The response message used for the + EchoErrorDetails method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.EchoErrorDetailsRequest): + request = gs_echo.EchoErrorDetailsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.echo_error_details] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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 + + def expand(self, + request: Optional[Union[gs_echo.ExpandRequest, dict]] = None, + *, + content: Optional[str] = None, + error: Optional[status_pb2.Status] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[gs_echo.EchoResponse]]: + r"""This method splits the given content into words and + will pass each word back through the stream. This method + showcases server-side streaming RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_expand(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ExpandRequest( + ) + + # Make the request + stream = await client.expand(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.ExpandRequest, dict]]): + The request object. The request message for the Expand + method. + content (:class:`str`): + The content that will be split into + words and returned on the stream. + + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + error (:class:`google.rpc.status_pb2.Status`): + The error that is thrown after all + words are sent on the stream. + + This corresponds to the ``error`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.showcase_v1beta1.types.EchoResponse]: + The response message for the Echo + methods. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [content, error] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.ExpandRequest): + request = gs_echo.ExpandRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if content is not None: + request.content = content + if error is not None: + request.error = error + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.expand] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect(self, + requests: Optional[AsyncIterator[gs_echo.EchoRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.EchoResponse: + r"""This method will collect the words given to it. When + the stream is closed by the client, this method will + return the a concatenation of the strings passed to it. + This method showcases client-side streaming RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_collect(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = await client.collect(requests=request_generator()) + + # Handle the response + print(response) + + Args: + requests (AsyncIterator[`google.showcase_v1beta1.types.EchoRequest`]): + The request object AsyncIterator. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.EchoResponse: + The response message for the Echo + methods. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.collect] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def chat(self, + requests: Optional[AsyncIterator[gs_echo.EchoRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[gs_echo.EchoResponse]]: + r"""This method, upon receiving a request on the stream, + will pass the same content back on the stream. This + method showcases bidirectional streaming RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_chat(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.chat(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.showcase_v1beta1.types.EchoRequest`]): + The request object AsyncIterator. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.showcase_v1beta1.types.EchoResponse]: + The response message for the Echo + methods. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.chat] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def paged_expand(self, + request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.PagedExpandAsyncPager: + r"""This is similar to the Expand method but instead of + returning a stream of expanded words, this method + returns a paged list of expanded words. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_paged_expand(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]]): + The request object. The request for the PagedExpand + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.echo.pagers.PagedExpandAsyncPager: + The response for the PagedExpand + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.PagedExpandRequest): + request = gs_echo.PagedExpandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.paged_expand] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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.PagedExpandAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def paged_expand_legacy(self, + request: Optional[Union[gs_echo.PagedExpandLegacyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.PagedExpandLegacyAsyncPager: + r"""This is similar to the PagedExpand except that it uses + max_results instead of page_size, as some legacy APIs still do. + New APIs should NOT use this pattern. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_paged_expand_legacy(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandLegacyRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.PagedExpandLegacyRequest, dict]]): + The request object. The request for the PagedExpandLegacy + method. This is a pattern used by some + legacy APIs. New APIs should NOT use + this pattern, but rather something like + PagedExpandRequest which conforms to + aip.dev/158. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyAsyncPager: + The response for the PagedExpand + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.PagedExpandLegacyRequest): + request = gs_echo.PagedExpandLegacyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.paged_expand_legacy] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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.PagedExpandLegacyAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def paged_expand_legacy_mapped(self, + request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.PagedExpandLegacyMappedAsyncPager: + r"""This method returns a map containing lists of words that appear + in the input, keyed by their initial character. The only words + returned are the ones included in the current page, as + determined by page_token and page_size, which both refer to the + word indices in the input. This paging result consisting of a + map of lists is a pattern used by some legacy APIs. New APIs + should NOT use this pattern. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_paged_expand_legacy_mapped(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy_mapped(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]]): + The request object. The request for the PagedExpand + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedAsyncPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.PagedExpandRequest): + request = gs_echo.PagedExpandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.paged_expand_legacy_mapped] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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.PagedExpandLegacyMappedAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def wait(self, + request: Optional[Union[gs_echo.WaitRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""This method will wait for the requested amount of + time and then return. This method showcases how a client + handles a request timeout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_wait(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.WaitRequest( + ) + + # Make the request + operation = await client.wait(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.WaitRequest, dict]]): + The request object. The request for Wait method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.showcase_v1beta1.types.WaitResponse` The + result of the Wait operation. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.WaitRequest): + request = gs_echo.WaitRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.wait] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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, + gs_echo.WaitResponse, + metadata_type=gs_echo.WaitMetadata, + ) + + # Done; return the response. + return response + + async def block(self, + request: Optional[Union[gs_echo.BlockRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.BlockResponse: + r"""This method will block (wait) for the requested + amount of time and then return the response or error. + This method showcases how a client handles delays or + retries. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_block(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.BlockRequest( + ) + + # Make the request + response = await client.block(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.BlockRequest, dict]]): + The request object. The request for Block method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.BlockResponse: + The response for Block method. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.BlockRequest): + request = gs_echo.BlockRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.block] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "EchoAsyncClient": + 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__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "EchoAsyncClient", +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py new file mode 100644 index 000000000000..5f5f09827e7c --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py @@ -0,0 +1,2361 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +import uuid +import warnings + +from google.showcase_v1beta1 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 +import google.protobuf +try: + from google.api_core import version_header + HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + HAS_GOOGLE_API_CORE_VERSION_HEADER = False + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.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.showcase_v1beta1.services.echo import pagers +from google.showcase_v1beta1.types import echo as gs_echo +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from .transports.base import EchoTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EchoGrpcTransport +from .transports.grpc_asyncio import EchoGrpcAsyncIOTransport +from .transports.rest import EchoRestTransport + + +class EchoClientMeta(type): + """Metaclass for the Echo 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[EchoTransport]] + _transport_registry["grpc"] = EchoGrpcTransport + _transport_registry["grpc_asyncio"] = EchoGrpcAsyncIOTransport + _transport_registry["rest"] = EchoRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EchoTransport]: + """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 EchoClient(metaclass=EchoClientMeta): + """This service is used showcase the four main types of rpcs - + unary, server side streaming, client side streaming, and + bidirectional streaming. This service also exposes methods that + explicitly implement server delay, and paginated calls. Set the + 'showcase-trailer' metadata key on any method to have the values + echoed in the response trailers. Set the 'x-goog-request-params' + metadata key on any method to have the values echoed in the + response headers. + This class implements API version v1_20240408.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "localhost:7469" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "localhost:7469" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EchoClient: 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: + EchoClient: 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) -> EchoTransport: + """Returns the transport used by the client instance. + + Returns: + EchoTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = EchoClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = EchoClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + """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 = EchoClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EchoClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EchoClient._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 = EchoClient._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 + + @staticmethod + def _setup_request_id(request, field_name: str, is_proto3_optional: bool): + """Populate a UUID4 field in the request if it is not already set. + + Args: + request (Union[google.protobuf.message.Message, dict]): The request object. + field_name (str): The name of the field to populate. + is_proto3_optional (bool): Whether the field is proto3 optional. + """ + if isinstance(request, dict): + if is_proto3_optional: + if field_name not in request: + request[field_name] = str(uuid.uuid4()) + elif not request.get(field_name): + request[field_name] = str(uuid.uuid4()) + return + + if is_proto3_optional: + try: + # Pure protobuf messages + if not request.HasField(field_name): + setattr(request, field_name, str(uuid.uuid4())) + except (AttributeError, ValueError): + # Proto-plus messages or other objects + if field_name not in request: + setattr(request, field_name, str(uuid.uuid4())) + else: + if not getattr(request, field_name): + setattr(request, field_name, str(uuid.uuid4())) + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """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, EchoTransport, Callable[..., EchoTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the echo client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. 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,EchoTransport,Callable[..., EchoTransport]]]): + 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 EchoTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = EchoClient._read_environment_variables() + self._client_cert_source = EchoClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EchoClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, EchoTransport) + if transport_provided: + # transport is a EchoTransport 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(EchoTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EchoClient._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[EchoTransport], Callable[..., EchoTransport]] = ( + EchoClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EchoTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.showcase_v1beta1.EchoClient`.", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.showcase.v1beta1.Echo", + "credentialsType": None, + } + ) + + def echo(self, + request: Optional[Union[gs_echo.EchoRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.EchoResponse: + r"""This method simply echoes the request. This method + showcases unary RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_echo(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # Make the request + response = client.echo(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.EchoRequest, dict]): + The request object. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.EchoResponse: + The response message for the Echo + methods. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.EchoRequest): + request = gs_echo.EchoRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.echo] + + header_params = {} + + if request.header: + header_params["header"] = request.header + + routing_param_regex = re.compile('^(?P.*)$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("routing_id"): + header_params["routing_id"] = regex_match.group("routing_id") + + routing_param_regex = re.compile('^(?Pregions/[^/]+/zones/[^/]+(?:/.*)?)$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("table_name"): + header_params["table_name"] = regex_match.group("table_name") + + routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("super_id"): + header_params["super_id"] = regex_match.group("super_id") + + routing_param_regex = re.compile('^(?Pprojects/[^/]+/instances/[^/]+(?:/.*)?)$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("table_name"): + header_params["table_name"] = regex_match.group("table_name") + + routing_param_regex = re.compile('^projects/[^/]+/(?Pinstances/[^/]+)(?:/.*)?$') + regex_match = routing_param_regex.match(request.header) + if regex_match and regex_match.group("instance_id"): + header_params["instance_id"] = regex_match.group("instance_id") + + routing_param_regex = re.compile('^(?P.*)$') + regex_match = routing_param_regex.match(request.other_header) + if regex_match and regex_match.group("baz"): + header_params["baz"] = regex_match.group("baz") + + routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') + regex_match = routing_param_regex.match(request.other_header) + if regex_match and regex_match.group("qux"): + header_params["qux"] = regex_match.group("qux") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + self._setup_request_id(request, 'request_id', False) + self._setup_request_id(request, 'other_request_id', True) + + # 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 echo_error_details(self, + request: Optional[Union[gs_echo.EchoErrorDetailsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.EchoErrorDetailsResponse: + r"""This method returns error details in a repeated + "google.protobuf.Any" field. This method showcases handling + errors thus encoded, particularly over REST transport. Note that + GAPICs only allow the type "google.protobuf.Any" for field paths + ending in "error.details", and, at run-time, the actual types + for these fields must be one of the types in + google/rpc/error_details.proto. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_echo_error_details(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoErrorDetailsRequest( + ) + + # Make the request + response = client.echo_error_details(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.EchoErrorDetailsRequest, dict]): + The request object. The request message used for the + EchoErrorDetails method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.EchoErrorDetailsResponse: + The response message used for the + EchoErrorDetails method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.EchoErrorDetailsRequest): + request = gs_echo.EchoErrorDetailsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.echo_error_details] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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 expand(self, + request: Optional[Union[gs_echo.ExpandRequest, dict]] = None, + *, + content: Optional[str] = None, + error: Optional[status_pb2.Status] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[gs_echo.EchoResponse]: + r"""This method splits the given content into words and + will pass each word back through the stream. This method + showcases server-side streaming RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_expand(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ExpandRequest( + ) + + # Make the request + stream = client.expand(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.ExpandRequest, dict]): + The request object. The request message for the Expand + method. + content (str): + The content that will be split into + words and returned on the stream. + + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + error (google.rpc.status_pb2.Status): + The error that is thrown after all + words are sent on the stream. + + This corresponds to the ``error`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.showcase_v1beta1.types.EchoResponse]: + The response message for the Echo + methods. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [content, error] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.ExpandRequest): + request = gs_echo.ExpandRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if content is not None: + request.content = content + if error is not None: + request.error = error + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.expand] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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 collect(self, + requests: Optional[Iterator[gs_echo.EchoRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.EchoResponse: + r"""This method will collect the words given to it. When + the stream is closed by the client, this method will + return the a concatenation of the strings passed to it. + This method showcases client-side streaming RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_collect(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = client.collect(requests=request_generator()) + + # Handle the response + print(response) + + Args: + requests (Iterator[google.showcase_v1beta1.types.EchoRequest]): + The request object iterator. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.EchoResponse: + The response message for the Echo + methods. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def chat(self, + requests: Optional[Iterator[gs_echo.EchoRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[gs_echo.EchoResponse]: + r"""This method, upon receiving a request on the stream, + will pass the same content back on the stream. This + method showcases bidirectional streaming RPCs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_chat(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.chat(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.showcase_v1beta1.types.EchoRequest]): + The request object iterator. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.showcase_v1beta1.types.EchoResponse]: + The response message for the Echo + methods. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.chat] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def paged_expand(self, + request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.PagedExpandPager: + r"""This is similar to the Expand method but instead of + returning a stream of expanded words, this method + returns a paged list of expanded words. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_paged_expand(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]): + The request object. The request for the PagedExpand + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.echo.pagers.PagedExpandPager: + The response for the PagedExpand + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.PagedExpandRequest): + request = gs_echo.PagedExpandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.paged_expand] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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.PagedExpandPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def paged_expand_legacy(self, + request: Optional[Union[gs_echo.PagedExpandLegacyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.PagedExpandLegacyPager: + r"""This is similar to the PagedExpand except that it uses + max_results instead of page_size, as some legacy APIs still do. + New APIs should NOT use this pattern. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_paged_expand_legacy(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandLegacyRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.PagedExpandLegacyRequest, dict]): + The request object. The request for the PagedExpandLegacy + method. This is a pattern used by some + legacy APIs. New APIs should NOT use + this pattern, but rather something like + PagedExpandRequest which conforms to + aip.dev/158. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyPager: + The response for the PagedExpand + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.PagedExpandLegacyRequest): + request = gs_echo.PagedExpandLegacyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.paged_expand_legacy] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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.PagedExpandLegacyPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def paged_expand_legacy_mapped(self, + request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.PagedExpandLegacyMappedPager: + r"""This method returns a map containing lists of words that appear + in the input, keyed by their initial character. The only words + returned are the ones included in the current page, as + determined by page_token and page_size, which both refer to the + word indices in the input. This paging result consisting of a + map of lists is a pattern used by some legacy APIs. New APIs + should NOT use this pattern. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_paged_expand_legacy_mapped(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy_mapped(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]): + The request object. The request for the PagedExpand + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.PagedExpandRequest): + request = gs_echo.PagedExpandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.paged_expand_legacy_mapped] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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.PagedExpandLegacyMappedPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def wait(self, + request: Optional[Union[gs_echo.WaitRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""This method will wait for the requested amount of + time and then return. This method showcases how a client + handles a request timeout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_wait(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.WaitRequest( + ) + + # Make the request + operation = client.wait(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.WaitRequest, dict]): + The request object. The request for Wait method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.showcase_v1beta1.types.WaitResponse` The + result of the Wait operation. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.WaitRequest): + request = gs_echo.WaitRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.wait] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # 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, + gs_echo.WaitResponse, + metadata_type=gs_echo.WaitMetadata, + ) + + # Done; return the response. + return response + + def block(self, + request: Optional[Union[gs_echo.BlockRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gs_echo.BlockResponse: + r"""This method will block (wait) for the requested + amount of time and then return the response or error. + This method showcases how a client handles delays or + retries. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_block(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.BlockRequest( + ) + + # Make the request + response = client.block(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.BlockRequest, dict]): + The request object. The request for Block method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.BlockResponse: + The response for Block method. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gs_echo.BlockRequest): + request = gs_echo.BlockRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.block] + + if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER + metadata = tuple(metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EchoClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "EchoClient", +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py new file mode 100644 index 000000000000..5a63f9b4d3f2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1.types import echo as gs_echo + + +class PagedExpandPager: + """A pager for iterating through ``paged_expand`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and + provides an ``__iter__`` method to iterate through its + ``responses`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``PagedExpand`` requests and continue to iterate + through the ``responses`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., gs_echo.PagedExpandResponse], + request: gs_echo.PagedExpandRequest, + response: gs_echo.PagedExpandResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.PagedExpandRequest): + The initial request object. + response (google.showcase_v1beta1.types.PagedExpandResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandResponse]: + 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[gs_echo.EchoResponse]: + for page in self.pages: + yield from page.responses + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PagedExpandAsyncPager: + """A pager for iterating through ``paged_expand`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``responses`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``PagedExpand`` requests and continue to iterate + through the ``responses`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` + attributes are available on the 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[gs_echo.PagedExpandResponse]], + request: gs_echo.PagedExpandRequest, + response: gs_echo.PagedExpandResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.PagedExpandRequest): + The initial request object. + response (google.showcase_v1beta1.types.PagedExpandResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandResponse]: + 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[gs_echo.EchoResponse]: + async def async_generator(): + async for page in self.pages: + for response in page.responses: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PagedExpandLegacyPager: + """A pager for iterating through ``paged_expand_legacy`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and + provides an ``__iter__`` method to iterate through its + ``responses`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``PagedExpandLegacy`` requests and continue to iterate + through the ``responses`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., gs_echo.PagedExpandResponse], + request: gs_echo.PagedExpandLegacyRequest, + response: gs_echo.PagedExpandResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.PagedExpandLegacyRequest): + The initial request object. + response (google.showcase_v1beta1.types.PagedExpandResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gs_echo.PagedExpandLegacyRequest(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[gs_echo.PagedExpandResponse]: + 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[gs_echo.EchoResponse]: + for page in self.pages: + yield from page.responses + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PagedExpandLegacyAsyncPager: + """A pager for iterating through ``paged_expand_legacy`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``responses`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``PagedExpandLegacy`` requests and continue to iterate + through the ``responses`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` + attributes are available on the 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[gs_echo.PagedExpandResponse]], + request: gs_echo.PagedExpandLegacyRequest, + response: gs_echo.PagedExpandResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.PagedExpandLegacyRequest): + The initial request object. + response (google.showcase_v1beta1.types.PagedExpandResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gs_echo.PagedExpandLegacyRequest(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[gs_echo.PagedExpandResponse]: + 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[gs_echo.EchoResponse]: + async def async_generator(): + async for page in self.pages: + for response in page.responses: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PagedExpandLegacyMappedPager: + """A pager for iterating through ``paged_expand_legacy_mapped`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` object, and + provides an ``__iter__`` method to iterate through its + ``alphabetized`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``PagedExpandLegacyMapped`` requests and continue to iterate + through the ``alphabetized`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., gs_echo.PagedExpandLegacyMappedResponse], + request: gs_echo.PagedExpandRequest, + response: gs_echo.PagedExpandLegacyMappedResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.PagedExpandRequest): + The initial request object. + response (google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandLegacyMappedResponse]: + 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[Tuple[str, gs_echo.PagedExpandResponseList]]: + for page in self.pages: + yield from page.alphabetized.items() + + def get(self, key: str) -> Optional[gs_echo.PagedExpandResponseList]: + return self._response.alphabetized.get(key) + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PagedExpandLegacyMappedAsyncPager: + """A pager for iterating through ``paged_expand_legacy_mapped`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``alphabetized`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``PagedExpandLegacyMapped`` requests and continue to iterate + through the ``alphabetized`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` + attributes are available on the 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[gs_echo.PagedExpandLegacyMappedResponse]], + request: gs_echo.PagedExpandRequest, + response: gs_echo.PagedExpandLegacyMappedResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.PagedExpandRequest): + The initial request object. + response (google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandLegacyMappedResponse]: + 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) -> Iterator[Tuple[str, gs_echo.PagedExpandResponseList]]: + async def async_generator(): + async for page in self.pages: + for response in page.alphabetized.items(): + yield response + + return async_generator() + + def get(self, key: str) -> Optional[gs_echo.PagedExpandResponseList]: + return self._response.alphabetized.get(key) + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst new file mode 100644 index 000000000000..05bef773a754 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``EchoTransport`` is the ABC for all transports. + +- public child ``EchoGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``EchoGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseEchoRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``EchoRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py new file mode 100644 index 000000000000..8a020e39cd6d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 EchoTransport +from .grpc import EchoGrpcTransport +from .grpc_asyncio import EchoGrpcAsyncIOTransport +from .rest import EchoRestTransport +from .rest import EchoRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EchoTransport]] +_transport_registry['grpc'] = EchoGrpcTransport +_transport_registry['grpc_asyncio'] = EchoGrpcAsyncIOTransport +_transport_registry['rest'] = EchoRestTransport + +__all__ = ( + 'EchoTransport', + 'EchoGrpcTransport', + 'EchoGrpcAsyncIOTransport', + 'EchoRestTransport', + 'EchoRestInterceptor', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py new file mode 100644 index 000000000000..1805bddee9af --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1 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 +import google.protobuf + +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.showcase_v1beta1.types import echo as gs_echo + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class EchoTransport(abc.ABC): + """Abstract transport class for Echo.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'localhost:7469' + + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.echo: gapic_v1.method.wrap_method( + self.echo, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.echo_error_details: gapic_v1.method.wrap_method( + self.echo_error_details, + default_timeout=None, + client_info=client_info, + ), + self.expand: gapic_v1.method.wrap_method( + self.expand, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.collect: gapic_v1.method.wrap_method( + self.collect, + default_timeout=None, + client_info=client_info, + ), + self.chat: gapic_v1.method.wrap_method( + self.chat, + default_timeout=None, + client_info=client_info, + ), + self.paged_expand: gapic_v1.method.wrap_method( + self.paged_expand, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.paged_expand_legacy: gapic_v1.method.wrap_method( + self.paged_expand_legacy, + default_timeout=None, + client_info=client_info, + ), + self.paged_expand_legacy_mapped: gapic_v1.method.wrap_method( + self.paged_expand_legacy_mapped, + default_timeout=None, + client_info=client_info, + ), + self.wait: gapic_v1.method.wrap_method( + self.wait, + default_timeout=None, + client_info=client_info, + ), + self.block: gapic_v1.method.wrap_method( + self.block, + 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_location: gapic_v1.method.wrap_method( + self.get_location, + 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.get_iam_policy: gapic_v1.method.wrap_method( + self.get_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.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + 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, + ), + } + + 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 echo(self) -> Callable[ + [gs_echo.EchoRequest], + Union[ + gs_echo.EchoResponse, + Awaitable[gs_echo.EchoResponse] + ]]: + raise NotImplementedError() + + @property + def echo_error_details(self) -> Callable[ + [gs_echo.EchoErrorDetailsRequest], + Union[ + gs_echo.EchoErrorDetailsResponse, + Awaitable[gs_echo.EchoErrorDetailsResponse] + ]]: + raise NotImplementedError() + + @property + def expand(self) -> Callable[ + [gs_echo.ExpandRequest], + Union[ + gs_echo.EchoResponse, + Awaitable[gs_echo.EchoResponse] + ]]: + raise NotImplementedError() + + @property + def collect(self) -> Callable[ + [gs_echo.EchoRequest], + Union[ + gs_echo.EchoResponse, + Awaitable[gs_echo.EchoResponse] + ]]: + raise NotImplementedError() + + @property + def chat(self) -> Callable[ + [gs_echo.EchoRequest], + Union[ + gs_echo.EchoResponse, + Awaitable[gs_echo.EchoResponse] + ]]: + raise NotImplementedError() + + @property + def paged_expand(self) -> Callable[ + [gs_echo.PagedExpandRequest], + Union[ + gs_echo.PagedExpandResponse, + Awaitable[gs_echo.PagedExpandResponse] + ]]: + raise NotImplementedError() + + @property + def paged_expand_legacy(self) -> Callable[ + [gs_echo.PagedExpandLegacyRequest], + Union[ + gs_echo.PagedExpandResponse, + Awaitable[gs_echo.PagedExpandResponse] + ]]: + raise NotImplementedError() + + @property + def paged_expand_legacy_mapped(self) -> Callable[ + [gs_echo.PagedExpandRequest], + Union[ + gs_echo.PagedExpandLegacyMappedResponse, + Awaitable[gs_echo.PagedExpandLegacyMappedResponse] + ]]: + raise NotImplementedError() + + @property + def wait(self) -> Callable[ + [gs_echo.WaitRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def block(self) -> Callable[ + [gs_echo.BlockRequest], + Union[ + gs_echo.BlockResponse, + Awaitable[gs_echo.BlockResponse] + ]]: + 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__ = ( + 'EchoTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py new file mode 100644 index 000000000000..f74aa619c4f6 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py @@ -0,0 +1,831 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.showcase_v1beta1.types import echo as gs_echo +from .base import EchoTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EchoGrpcTransport(EchoTransport): + """gRPC backend transport for Echo. + + This service is used showcase the four main types of rpcs - + unary, server side streaming, client side streaming, and + bidirectional streaming. This service also exposes methods that + explicitly implement server delay, and paginated calls. Set the + 'showcase-trailer' metadata key on any method to have the values + echoed in the response trailers. Set the 'x-goog-request-params' + metadata key on any method to have the values echoed in the + response headers. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'localhost:7469', + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'localhost:7469', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def echo(self) -> Callable[ + [gs_echo.EchoRequest], + gs_echo.EchoResponse]: + r"""Return a callable for the echo method over gRPC. + + This method simply echoes the request. This method + showcases unary RPCs. + + Returns: + Callable[[~.EchoRequest], + ~.EchoResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'echo' not in self._stubs: + self._stubs['echo'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/Echo', + request_serializer=gs_echo.EchoRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['echo'] + + @property + def echo_error_details(self) -> Callable[ + [gs_echo.EchoErrorDetailsRequest], + gs_echo.EchoErrorDetailsResponse]: + r"""Return a callable for the echo error details method over gRPC. + + This method returns error details in a repeated + "google.protobuf.Any" field. This method showcases handling + errors thus encoded, particularly over REST transport. Note that + GAPICs only allow the type "google.protobuf.Any" for field paths + ending in "error.details", and, at run-time, the actual types + for these fields must be one of the types in + google/rpc/error_details.proto. + + Returns: + Callable[[~.EchoErrorDetailsRequest], + ~.EchoErrorDetailsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'echo_error_details' not in self._stubs: + self._stubs['echo_error_details'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/EchoErrorDetails', + request_serializer=gs_echo.EchoErrorDetailsRequest.serialize, + response_deserializer=gs_echo.EchoErrorDetailsResponse.deserialize, + ) + return self._stubs['echo_error_details'] + + @property + def expand(self) -> Callable[ + [gs_echo.ExpandRequest], + gs_echo.EchoResponse]: + r"""Return a callable for the expand method over gRPC. + + This method splits the given content into words and + will pass each word back through the stream. This method + showcases server-side streaming RPCs. + + Returns: + Callable[[~.ExpandRequest], + ~.EchoResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'expand' not in self._stubs: + self._stubs['expand'] = self._logged_channel.unary_stream( + '/google.showcase.v1beta1.Echo/Expand', + request_serializer=gs_echo.ExpandRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['expand'] + + @property + def collect(self) -> Callable[ + [gs_echo.EchoRequest], + gs_echo.EchoResponse]: + r"""Return a callable for the collect method over gRPC. + + This method will collect the words given to it. When + the stream is closed by the client, this method will + return the a concatenation of the strings passed to it. + This method showcases client-side streaming RPCs. + + Returns: + Callable[[~.EchoRequest], + ~.EchoResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect' not in self._stubs: + self._stubs['collect'] = self._logged_channel.stream_unary( + '/google.showcase.v1beta1.Echo/Collect', + request_serializer=gs_echo.EchoRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['collect'] + + @property + def chat(self) -> Callable[ + [gs_echo.EchoRequest], + gs_echo.EchoResponse]: + r"""Return a callable for the chat method over gRPC. + + This method, upon receiving a request on the stream, + will pass the same content back on the stream. This + method showcases bidirectional streaming RPCs. + + Returns: + Callable[[~.EchoRequest], + ~.EchoResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'chat' not in self._stubs: + self._stubs['chat'] = self._logged_channel.stream_stream( + '/google.showcase.v1beta1.Echo/Chat', + request_serializer=gs_echo.EchoRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['chat'] + + @property + def paged_expand(self) -> Callable[ + [gs_echo.PagedExpandRequest], + gs_echo.PagedExpandResponse]: + r"""Return a callable for the paged expand method over gRPC. + + This is similar to the Expand method but instead of + returning a stream of expanded words, this method + returns a paged list of expanded words. + + Returns: + Callable[[~.PagedExpandRequest], + ~.PagedExpandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'paged_expand' not in self._stubs: + self._stubs['paged_expand'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/PagedExpand', + request_serializer=gs_echo.PagedExpandRequest.serialize, + response_deserializer=gs_echo.PagedExpandResponse.deserialize, + ) + return self._stubs['paged_expand'] + + @property + def paged_expand_legacy(self) -> Callable[ + [gs_echo.PagedExpandLegacyRequest], + gs_echo.PagedExpandResponse]: + r"""Return a callable for the paged expand legacy method over gRPC. + + This is similar to the PagedExpand except that it uses + max_results instead of page_size, as some legacy APIs still do. + New APIs should NOT use this pattern. + + Returns: + Callable[[~.PagedExpandLegacyRequest], + ~.PagedExpandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'paged_expand_legacy' not in self._stubs: + self._stubs['paged_expand_legacy'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/PagedExpandLegacy', + request_serializer=gs_echo.PagedExpandLegacyRequest.serialize, + response_deserializer=gs_echo.PagedExpandResponse.deserialize, + ) + return self._stubs['paged_expand_legacy'] + + @property + def paged_expand_legacy_mapped(self) -> Callable[ + [gs_echo.PagedExpandRequest], + gs_echo.PagedExpandLegacyMappedResponse]: + r"""Return a callable for the paged expand legacy mapped method over gRPC. + + This method returns a map containing lists of words that appear + in the input, keyed by their initial character. The only words + returned are the ones included in the current page, as + determined by page_token and page_size, which both refer to the + word indices in the input. This paging result consisting of a + map of lists is a pattern used by some legacy APIs. New APIs + should NOT use this pattern. + + Returns: + Callable[[~.PagedExpandRequest], + ~.PagedExpandLegacyMappedResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'paged_expand_legacy_mapped' not in self._stubs: + self._stubs['paged_expand_legacy_mapped'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/PagedExpandLegacyMapped', + request_serializer=gs_echo.PagedExpandRequest.serialize, + response_deserializer=gs_echo.PagedExpandLegacyMappedResponse.deserialize, + ) + return self._stubs['paged_expand_legacy_mapped'] + + @property + def wait(self) -> Callable[ + [gs_echo.WaitRequest], + operations_pb2.Operation]: + r"""Return a callable for the wait method over gRPC. + + This method will wait for the requested amount of + time and then return. This method showcases how a client + handles a request timeout. + + Returns: + Callable[[~.WaitRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'wait' not in self._stubs: + self._stubs['wait'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/Wait', + request_serializer=gs_echo.WaitRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['wait'] + + @property + def block(self) -> Callable[ + [gs_echo.BlockRequest], + gs_echo.BlockResponse]: + r"""Return a callable for the block method over gRPC. + + This method will block (wait) for the requested + amount of time and then return the response or error. + This method showcases how a client handles delays or + retries. + + Returns: + Callable[[~.BlockRequest], + ~.BlockResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'block' not in self._stubs: + self._stubs['block'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/Block', + request_serializer=gs_echo.BlockRequest.serialize, + response_deserializer=gs_echo.BlockResponse.deserialize, + ) + return self._stubs['block'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'EchoGrpcTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py new file mode 100644 index 000000000000..a7bd21b9e0ab --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py @@ -0,0 +1,972 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.showcase_v1beta1.types import echo as gs_echo +from .base import EchoTransport, DEFAULT_CLIENT_INFO +from .grpc import EchoGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EchoGrpcAsyncIOTransport(EchoTransport): + """gRPC AsyncIO backend transport for Echo. + + This service is used showcase the four main types of rpcs - + unary, server side streaming, client side streaming, and + bidirectional streaming. This service also exposes methods that + explicitly implement server delay, and paginated calls. Set the + 'showcase-trailer' metadata key on any method to have the values + echoed in the response trailers. Set the 'x-goog-request-params' + metadata key on any method to have the values echoed in the + response headers. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'localhost:7469', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'localhost:7469', + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def echo(self) -> Callable[ + [gs_echo.EchoRequest], + Awaitable[gs_echo.EchoResponse]]: + r"""Return a callable for the echo method over gRPC. + + This method simply echoes the request. This method + showcases unary RPCs. + + Returns: + Callable[[~.EchoRequest], + Awaitable[~.EchoResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'echo' not in self._stubs: + self._stubs['echo'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/Echo', + request_serializer=gs_echo.EchoRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['echo'] + + @property + def echo_error_details(self) -> Callable[ + [gs_echo.EchoErrorDetailsRequest], + Awaitable[gs_echo.EchoErrorDetailsResponse]]: + r"""Return a callable for the echo error details method over gRPC. + + This method returns error details in a repeated + "google.protobuf.Any" field. This method showcases handling + errors thus encoded, particularly over REST transport. Note that + GAPICs only allow the type "google.protobuf.Any" for field paths + ending in "error.details", and, at run-time, the actual types + for these fields must be one of the types in + google/rpc/error_details.proto. + + Returns: + Callable[[~.EchoErrorDetailsRequest], + Awaitable[~.EchoErrorDetailsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'echo_error_details' not in self._stubs: + self._stubs['echo_error_details'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/EchoErrorDetails', + request_serializer=gs_echo.EchoErrorDetailsRequest.serialize, + response_deserializer=gs_echo.EchoErrorDetailsResponse.deserialize, + ) + return self._stubs['echo_error_details'] + + @property + def expand(self) -> Callable[ + [gs_echo.ExpandRequest], + Awaitable[gs_echo.EchoResponse]]: + r"""Return a callable for the expand method over gRPC. + + This method splits the given content into words and + will pass each word back through the stream. This method + showcases server-side streaming RPCs. + + Returns: + Callable[[~.ExpandRequest], + Awaitable[~.EchoResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'expand' not in self._stubs: + self._stubs['expand'] = self._logged_channel.unary_stream( + '/google.showcase.v1beta1.Echo/Expand', + request_serializer=gs_echo.ExpandRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['expand'] + + @property + def collect(self) -> Callable[ + [gs_echo.EchoRequest], + Awaitable[gs_echo.EchoResponse]]: + r"""Return a callable for the collect method over gRPC. + + This method will collect the words given to it. When + the stream is closed by the client, this method will + return the a concatenation of the strings passed to it. + This method showcases client-side streaming RPCs. + + Returns: + Callable[[~.EchoRequest], + Awaitable[~.EchoResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect' not in self._stubs: + self._stubs['collect'] = self._logged_channel.stream_unary( + '/google.showcase.v1beta1.Echo/Collect', + request_serializer=gs_echo.EchoRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['collect'] + + @property + def chat(self) -> Callable[ + [gs_echo.EchoRequest], + Awaitable[gs_echo.EchoResponse]]: + r"""Return a callable for the chat method over gRPC. + + This method, upon receiving a request on the stream, + will pass the same content back on the stream. This + method showcases bidirectional streaming RPCs. + + Returns: + Callable[[~.EchoRequest], + Awaitable[~.EchoResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'chat' not in self._stubs: + self._stubs['chat'] = self._logged_channel.stream_stream( + '/google.showcase.v1beta1.Echo/Chat', + request_serializer=gs_echo.EchoRequest.serialize, + response_deserializer=gs_echo.EchoResponse.deserialize, + ) + return self._stubs['chat'] + + @property + def paged_expand(self) -> Callable[ + [gs_echo.PagedExpandRequest], + Awaitable[gs_echo.PagedExpandResponse]]: + r"""Return a callable for the paged expand method over gRPC. + + This is similar to the Expand method but instead of + returning a stream of expanded words, this method + returns a paged list of expanded words. + + Returns: + Callable[[~.PagedExpandRequest], + Awaitable[~.PagedExpandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'paged_expand' not in self._stubs: + self._stubs['paged_expand'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/PagedExpand', + request_serializer=gs_echo.PagedExpandRequest.serialize, + response_deserializer=gs_echo.PagedExpandResponse.deserialize, + ) + return self._stubs['paged_expand'] + + @property + def paged_expand_legacy(self) -> Callable[ + [gs_echo.PagedExpandLegacyRequest], + Awaitable[gs_echo.PagedExpandResponse]]: + r"""Return a callable for the paged expand legacy method over gRPC. + + This is similar to the PagedExpand except that it uses + max_results instead of page_size, as some legacy APIs still do. + New APIs should NOT use this pattern. + + Returns: + Callable[[~.PagedExpandLegacyRequest], + Awaitable[~.PagedExpandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'paged_expand_legacy' not in self._stubs: + self._stubs['paged_expand_legacy'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/PagedExpandLegacy', + request_serializer=gs_echo.PagedExpandLegacyRequest.serialize, + response_deserializer=gs_echo.PagedExpandResponse.deserialize, + ) + return self._stubs['paged_expand_legacy'] + + @property + def paged_expand_legacy_mapped(self) -> Callable[ + [gs_echo.PagedExpandRequest], + Awaitable[gs_echo.PagedExpandLegacyMappedResponse]]: + r"""Return a callable for the paged expand legacy mapped method over gRPC. + + This method returns a map containing lists of words that appear + in the input, keyed by their initial character. The only words + returned are the ones included in the current page, as + determined by page_token and page_size, which both refer to the + word indices in the input. This paging result consisting of a + map of lists is a pattern used by some legacy APIs. New APIs + should NOT use this pattern. + + Returns: + Callable[[~.PagedExpandRequest], + Awaitable[~.PagedExpandLegacyMappedResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'paged_expand_legacy_mapped' not in self._stubs: + self._stubs['paged_expand_legacy_mapped'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/PagedExpandLegacyMapped', + request_serializer=gs_echo.PagedExpandRequest.serialize, + response_deserializer=gs_echo.PagedExpandLegacyMappedResponse.deserialize, + ) + return self._stubs['paged_expand_legacy_mapped'] + + @property + def wait(self) -> Callable[ + [gs_echo.WaitRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the wait method over gRPC. + + This method will wait for the requested amount of + time and then return. This method showcases how a client + handles a request timeout. + + Returns: + Callable[[~.WaitRequest], + 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 'wait' not in self._stubs: + self._stubs['wait'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/Wait', + request_serializer=gs_echo.WaitRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['wait'] + + @property + def block(self) -> Callable[ + [gs_echo.BlockRequest], + Awaitable[gs_echo.BlockResponse]]: + r"""Return a callable for the block method over gRPC. + + This method will block (wait) for the requested + amount of time and then return the response or error. + This method showcases how a client handles delays or + retries. + + Returns: + Callable[[~.BlockRequest], + Awaitable[~.BlockResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'block' not in self._stubs: + self._stubs['block'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Echo/Block', + request_serializer=gs_echo.BlockRequest.serialize, + response_deserializer=gs_echo.BlockResponse.deserialize, + ) + return self._stubs['block'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.echo: self._wrap_method( + self.echo, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.echo_error_details: self._wrap_method( + self.echo_error_details, + default_timeout=None, + client_info=client_info, + ), + self.expand: self._wrap_method( + self.expand, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.collect: self._wrap_method( + self.collect, + default_timeout=None, + client_info=client_info, + ), + self.chat: self._wrap_method( + self.chat, + default_timeout=None, + client_info=client_info, + ), + self.paged_expand: self._wrap_method( + self.paged_expand, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.paged_expand_legacy: self._wrap_method( + self.paged_expand_legacy, + default_timeout=None, + client_info=client_info, + ), + self.paged_expand_legacy_mapped: self._wrap_method( + self.paged_expand_legacy_mapped, + default_timeout=None, + client_info=client_info, + ), + self.wait: self._wrap_method( + self.wait, + default_timeout=None, + client_info=client_info, + ), + self.block: self._wrap_method( + self.block, + 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_location: self._wrap_method( + self.get_location, + 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.get_iam_policy: self._wrap_method( + self.get_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.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_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.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'EchoGrpcAsyncIOTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py new file mode 100644 index 000000000000..ade0c516ae2f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py @@ -0,0 +1,2975 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # 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.showcase_v1beta1 import _compat as rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +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.showcase_v1beta1.types import echo as gs_echo +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseEchoRestTransport +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 + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class EchoRestInterceptor: + """Interceptor for Echo. + + 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 EchoRestTransport. + + .. code-block:: python + class MyCustomEchoInterceptor(EchoRestInterceptor): + def pre_block(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_block(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_echo(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_echo(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_echo_error_details(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_echo_error_details(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_expand(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_expand(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_paged_expand(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_paged_expand(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_paged_expand_legacy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_paged_expand_legacy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_paged_expand_legacy_mapped(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_paged_expand_legacy_mapped(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_wait(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_wait(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EchoRestTransport(interceptor=MyCustomEchoInterceptor()) + client = EchoClient(transport=transport) + + + """ + def pre_block(self, request: gs_echo.BlockRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.BlockRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for block + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_block(self, response: gs_echo.BlockResponse) -> gs_echo.BlockResponse: + """Post-rpc interceptor for block + + DEPRECATED. Please use the `post_block_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_block` interceptor runs + before the `post_block_with_metadata` interceptor. + """ + return response + + def post_block_with_metadata(self, response: gs_echo.BlockResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.BlockResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for block + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_block_with_metadata` + interceptor in new development instead of the `post_block` interceptor. + When both interceptors are used, this `post_block_with_metadata` interceptor runs after the + `post_block` interceptor. The (possibly modified) response returned by + `post_block` will be passed to + `post_block_with_metadata`. + """ + return response, metadata + + def pre_echo(self, request: gs_echo.EchoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for echo + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_echo(self, response: gs_echo.EchoResponse) -> gs_echo.EchoResponse: + """Post-rpc interceptor for echo + + DEPRECATED. Please use the `post_echo_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_echo` interceptor runs + before the `post_echo_with_metadata` interceptor. + """ + return response + + def post_echo_with_metadata(self, response: gs_echo.EchoResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for echo + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_echo_with_metadata` + interceptor in new development instead of the `post_echo` interceptor. + When both interceptors are used, this `post_echo_with_metadata` interceptor runs after the + `post_echo` interceptor. The (possibly modified) response returned by + `post_echo` will be passed to + `post_echo_with_metadata`. + """ + return response, metadata + + def pre_echo_error_details(self, request: gs_echo.EchoErrorDetailsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoErrorDetailsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for echo_error_details + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_echo_error_details(self, response: gs_echo.EchoErrorDetailsResponse) -> gs_echo.EchoErrorDetailsResponse: + """Post-rpc interceptor for echo_error_details + + DEPRECATED. Please use the `post_echo_error_details_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_echo_error_details` interceptor runs + before the `post_echo_error_details_with_metadata` interceptor. + """ + return response + + def post_echo_error_details_with_metadata(self, response: gs_echo.EchoErrorDetailsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoErrorDetailsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for echo_error_details + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_echo_error_details_with_metadata` + interceptor in new development instead of the `post_echo_error_details` interceptor. + When both interceptors are used, this `post_echo_error_details_with_metadata` interceptor runs after the + `post_echo_error_details` interceptor. The (possibly modified) response returned by + `post_echo_error_details` will be passed to + `post_echo_error_details_with_metadata`. + """ + return response, metadata + + def pre_expand(self, request: gs_echo.ExpandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.ExpandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for expand + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_expand(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for expand + + DEPRECATED. Please use the `post_expand_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_expand` interceptor runs + before the `post_expand_with_metadata` interceptor. + """ + return response + + def post_expand_with_metadata(self, response: rest_streaming.ResponseIterator, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for expand + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_expand_with_metadata` + interceptor in new development instead of the `post_expand` interceptor. + When both interceptors are used, this `post_expand_with_metadata` interceptor runs after the + `post_expand` interceptor. The (possibly modified) response returned by + `post_expand` will be passed to + `post_expand_with_metadata`. + """ + return response, metadata + + def pre_paged_expand(self, request: gs_echo.PagedExpandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for paged_expand + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_paged_expand(self, response: gs_echo.PagedExpandResponse) -> gs_echo.PagedExpandResponse: + """Post-rpc interceptor for paged_expand + + DEPRECATED. Please use the `post_paged_expand_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_paged_expand` interceptor runs + before the `post_paged_expand_with_metadata` interceptor. + """ + return response + + def post_paged_expand_with_metadata(self, response: gs_echo.PagedExpandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for paged_expand + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_paged_expand_with_metadata` + interceptor in new development instead of the `post_paged_expand` interceptor. + When both interceptors are used, this `post_paged_expand_with_metadata` interceptor runs after the + `post_paged_expand` interceptor. The (possibly modified) response returned by + `post_paged_expand` will be passed to + `post_paged_expand_with_metadata`. + """ + return response, metadata + + def pre_paged_expand_legacy(self, request: gs_echo.PagedExpandLegacyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandLegacyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for paged_expand_legacy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_paged_expand_legacy(self, response: gs_echo.PagedExpandResponse) -> gs_echo.PagedExpandResponse: + """Post-rpc interceptor for paged_expand_legacy + + DEPRECATED. Please use the `post_paged_expand_legacy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_paged_expand_legacy` interceptor runs + before the `post_paged_expand_legacy_with_metadata` interceptor. + """ + return response + + def post_paged_expand_legacy_with_metadata(self, response: gs_echo.PagedExpandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for paged_expand_legacy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_paged_expand_legacy_with_metadata` + interceptor in new development instead of the `post_paged_expand_legacy` interceptor. + When both interceptors are used, this `post_paged_expand_legacy_with_metadata` interceptor runs after the + `post_paged_expand_legacy` interceptor. The (possibly modified) response returned by + `post_paged_expand_legacy` will be passed to + `post_paged_expand_legacy_with_metadata`. + """ + return response, metadata + + def pre_paged_expand_legacy_mapped(self, request: gs_echo.PagedExpandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for paged_expand_legacy_mapped + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_paged_expand_legacy_mapped(self, response: gs_echo.PagedExpandLegacyMappedResponse) -> gs_echo.PagedExpandLegacyMappedResponse: + """Post-rpc interceptor for paged_expand_legacy_mapped + + DEPRECATED. Please use the `post_paged_expand_legacy_mapped_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_paged_expand_legacy_mapped` interceptor runs + before the `post_paged_expand_legacy_mapped_with_metadata` interceptor. + """ + return response + + def post_paged_expand_legacy_mapped_with_metadata(self, response: gs_echo.PagedExpandLegacyMappedResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandLegacyMappedResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for paged_expand_legacy_mapped + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_paged_expand_legacy_mapped_with_metadata` + interceptor in new development instead of the `post_paged_expand_legacy_mapped` interceptor. + When both interceptors are used, this `post_paged_expand_legacy_mapped_with_metadata` interceptor runs after the + `post_paged_expand_legacy_mapped` interceptor. The (possibly modified) response returned by + `post_paged_expand_legacy_mapped` will be passed to + `post_paged_expand_legacy_mapped_with_metadata`. + """ + return response, metadata + + def pre_wait(self, request: gs_echo.WaitRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.WaitRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for wait + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo server. + """ + return request, metadata + + def post_wait(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for wait + + DEPRECATED. Please use the `post_wait_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Echo server but before + it is returned to user code. This `post_wait` interceptor runs + before the `post_wait_with_metadata` interceptor. + """ + return response + + def post_wait_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for wait + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Echo server but before it is returned to user code. + + We recommend only using this `post_wait_with_metadata` + interceptor in new development instead of the `post_wait` interceptor. + When both interceptors are used, this `post_wait_with_metadata` interceptor runs after the + `post_wait` interceptor. The (possibly modified) response returned by + `post_wait` will be passed to + `post_wait_with_metadata`. + """ + return response, metadata + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Echo 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 Echo server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EchoRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EchoRestInterceptor + + +class EchoRestTransport(_BaseEchoRestTransport): + """REST backend synchronous transport for Echo. + + This service is used showcase the four main types of rpcs - + unary, server side streaming, client side streaming, and + bidirectional streaming. This service also exposes methods that + explicitly implement server delay, and paginated calls. Set the + 'showcase-trailer' metadata key on any method to have the values + echoed in the response trailers. Set the 'x-goog-request-params' + metadata key on any method to have the values echoed in the + response headers. + + This 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 = 'localhost:7469', + 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[EchoRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[EchoRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 EchoRestInterceptor() + 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.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/operations', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=operations/**}', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta1/{name=operations/**}', + }, + ], + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta1/{name=operations/**}:cancel', + }, + ], + } + + 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="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _Block(_BaseEchoRestTransport._BaseBlock, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.Block") + + @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: gs_echo.BlockRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.BlockResponse: + r"""Call the block method over HTTP. + + Args: + request (~.gs_echo.BlockRequest): + The request object. The request for Block method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.BlockResponse: + The response for Block method. + """ + + http_options = _BaseEchoRestTransport._BaseBlock._get_http_options() + request, metadata = self._interceptor.pre_block(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseBlock, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.Block", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Block", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._Block._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 = gs_echo.BlockResponse() + pb_resp = gs_echo.BlockResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_block(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_block_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gs_echo.BlockResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.block", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Block", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Chat(_BaseEchoRestTransport._BaseChat, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.Chat") + + def __call__(self, + request: gs_echo.EchoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method Chat is not available over REST transport" + ) + class _Collect(_BaseEchoRestTransport._BaseCollect, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.Collect") + + def __call__(self, + request: gs_echo.EchoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.EchoResponse: + raise NotImplementedError( + "Method Collect is not available over REST transport" + ) + class _Echo(_BaseEchoRestTransport._BaseEcho, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.Echo") + + @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: gs_echo.EchoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.EchoResponse: + r"""Call the echo method over HTTP. + + Args: + request (~.gs_echo.EchoRequest): + The request object. The request message used for the + Echo, Collect and Chat methods. If + content or opt are set in this message + then the request will succeed. If status + is set in this message then the status + will be returned as an error. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.EchoResponse: + The response message for the Echo + methods. + + """ + + http_options = _BaseEchoRestTransport._BaseEcho._get_http_options() + request, metadata = self._interceptor.pre_echo(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseEcho, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.Echo", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Echo", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._Echo._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 = gs_echo.EchoResponse() + pb_resp = gs_echo.EchoResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_echo(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_echo_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gs_echo.EchoResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.echo", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Echo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _EchoErrorDetails(_BaseEchoRestTransport._BaseEchoErrorDetails, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.EchoErrorDetails") + + @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: gs_echo.EchoErrorDetailsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.EchoErrorDetailsResponse: + r"""Call the echo error details method over HTTP. + + Args: + request (~.gs_echo.EchoErrorDetailsRequest): + The request object. The request message used for the + EchoErrorDetails method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.EchoErrorDetailsResponse: + The response message used for the + EchoErrorDetails method. + + """ + + http_options = _BaseEchoRestTransport._BaseEchoErrorDetails._get_http_options() + request, metadata = self._interceptor.pre_echo_error_details(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseEchoErrorDetails, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.EchoErrorDetails", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "EchoErrorDetails", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._EchoErrorDetails._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 = gs_echo.EchoErrorDetailsResponse() + pb_resp = gs_echo.EchoErrorDetailsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_echo_error_details(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_echo_error_details_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gs_echo.EchoErrorDetailsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.echo_error_details", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "EchoErrorDetails", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Expand(_BaseEchoRestTransport._BaseExpand, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.Expand") + + @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, + stream=True, + ) + return response + + def __call__(self, + request: gs_echo.ExpandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the expand method over HTTP. + + Args: + request (~.gs_echo.ExpandRequest): + The request object. The request message for the Expand + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.EchoResponse: + The response message for the Echo + methods. + + """ + + http_options = _BaseEchoRestTransport._BaseExpand._get_http_options() + request, metadata = self._interceptor.pre_expand(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseExpand, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.Expand", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Expand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._Expand._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 = rest_streaming.ResponseIterator(response, gs_echo.EchoResponse) + + resp = self._interceptor.post_expand(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_expand_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + http_response = { + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.expand", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Expand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PagedExpand(_BaseEchoRestTransport._BasePagedExpand, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.PagedExpand") + + @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: gs_echo.PagedExpandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.PagedExpandResponse: + r"""Call the paged expand method over HTTP. + + Args: + request (~.gs_echo.PagedExpandRequest): + The request object. The request for the PagedExpand + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.PagedExpandResponse: + The response for the PagedExpand + method. + + """ + + http_options = _BaseEchoRestTransport._BasePagedExpand._get_http_options() + request, metadata = self._interceptor.pre_paged_expand(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BasePagedExpand, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.PagedExpand", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "PagedExpand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._PagedExpand._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 = gs_echo.PagedExpandResponse() + pb_resp = gs_echo.PagedExpandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_paged_expand(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_paged_expand_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gs_echo.PagedExpandResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.paged_expand", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "PagedExpand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PagedExpandLegacy(_BaseEchoRestTransport._BasePagedExpandLegacy, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.PagedExpandLegacy") + + @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: gs_echo.PagedExpandLegacyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.PagedExpandResponse: + r"""Call the paged expand legacy method over HTTP. + + Args: + request (~.gs_echo.PagedExpandLegacyRequest): + The request object. The request for the PagedExpandLegacy + method. This is a pattern used by some + legacy APIs. New APIs should NOT use + this pattern, but rather something like + PagedExpandRequest which conforms to + aip.dev/158. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.PagedExpandResponse: + The response for the PagedExpand + method. + + """ + + http_options = _BaseEchoRestTransport._BasePagedExpandLegacy._get_http_options() + request, metadata = self._interceptor.pre_paged_expand_legacy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BasePagedExpandLegacy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.PagedExpandLegacy", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "PagedExpandLegacy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._PagedExpandLegacy._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 = gs_echo.PagedExpandResponse() + pb_resp = gs_echo.PagedExpandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_paged_expand_legacy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_paged_expand_legacy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gs_echo.PagedExpandResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.paged_expand_legacy", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "PagedExpandLegacy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PagedExpandLegacyMapped(_BaseEchoRestTransport._BasePagedExpandLegacyMapped, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.PagedExpandLegacyMapped") + + @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: gs_echo.PagedExpandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gs_echo.PagedExpandLegacyMappedResponse: + r"""Call the paged expand legacy + mapped method over HTTP. + + Args: + request (~.gs_echo.PagedExpandRequest): + The request object. The request for the PagedExpand + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gs_echo.PagedExpandLegacyMappedResponse: + + """ + + http_options = _BaseEchoRestTransport._BasePagedExpandLegacyMapped._get_http_options() + request, metadata = self._interceptor.pre_paged_expand_legacy_mapped(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BasePagedExpandLegacyMapped, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.PagedExpandLegacyMapped", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "PagedExpandLegacyMapped", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._PagedExpandLegacyMapped._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 = gs_echo.PagedExpandLegacyMappedResponse() + pb_resp = gs_echo.PagedExpandLegacyMappedResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_paged_expand_legacy_mapped(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_paged_expand_legacy_mapped_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gs_echo.PagedExpandLegacyMappedResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.paged_expand_legacy_mapped", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "PagedExpandLegacyMapped", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Wait(_BaseEchoRestTransport._BaseWait, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.Wait") + + @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: gs_echo.WaitRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the wait method over HTTP. + + Args: + request (~.gs_echo.WaitRequest): + The request object. The request for Wait method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEchoRestTransport._BaseWait._get_http_options() + request, metadata = self._interceptor.pre_wait(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseWait, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.Wait", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Wait", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._Wait._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_wait(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_wait_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoClient.wait", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "Wait", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def block(self) -> Callable[ + [gs_echo.BlockRequest], + gs_echo.BlockResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Block(self._session, self._host, self._interceptor) # type: ignore + + @property + def chat(self) -> Callable[ + [gs_echo.EchoRequest], + gs_echo.EchoResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Chat(self._session, self._host, self._interceptor) # type: ignore + + @property + def collect(self) -> Callable[ + [gs_echo.EchoRequest], + gs_echo.EchoResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Collect(self._session, self._host, self._interceptor) # type: ignore + + @property + def echo(self) -> Callable[ + [gs_echo.EchoRequest], + gs_echo.EchoResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Echo(self._session, self._host, self._interceptor) # type: ignore + + @property + def echo_error_details(self) -> Callable[ + [gs_echo.EchoErrorDetailsRequest], + gs_echo.EchoErrorDetailsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EchoErrorDetails(self._session, self._host, self._interceptor) # type: ignore + + @property + def expand(self) -> Callable[ + [gs_echo.ExpandRequest], + gs_echo.EchoResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Expand(self._session, self._host, self._interceptor) # type: ignore + + @property + def paged_expand(self) -> Callable[ + [gs_echo.PagedExpandRequest], + gs_echo.PagedExpandResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PagedExpand(self._session, self._host, self._interceptor) # type: ignore + + @property + def paged_expand_legacy(self) -> Callable[ + [gs_echo.PagedExpandLegacyRequest], + gs_echo.PagedExpandResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PagedExpandLegacy(self._session, self._host, self._interceptor) # type: ignore + + @property + def paged_expand_legacy_mapped(self) -> Callable[ + [gs_echo.PagedExpandRequest], + gs_echo.PagedExpandLegacyMappedResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PagedExpandLegacyMapped(self._session, self._host, self._interceptor) # type: ignore + + @property + def wait(self) -> Callable[ + [gs_echo.WaitRequest], + 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._Wait(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseEchoRestTransport._BaseListLocations, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseEchoRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseListLocations, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.ListLocations", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.ListLocations", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseEchoRestTransport._BaseGetLocation, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseEchoRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseGetLocation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.GetLocation", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.GetLocation", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseEchoRestTransport._BaseSetIamPolicy, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseEchoRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseSetIamPolicy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.SetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseEchoRestTransport._BaseGetIamPolicy, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseEchoRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseGetIamPolicy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.GetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseEchoRestTransport._BaseTestIamPermissions, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseEchoRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseTestIamPermissions, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.TestIamPermissions", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseEchoRestTransport._BaseListOperations, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseEchoRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseListOperations, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.ListOperations", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.ListOperations", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseEchoRestTransport._BaseGetOperation, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseEchoRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseGetOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.GetOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.EchoAsyncClient.GetOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseEchoRestTransport._BaseDeleteOperation, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEchoRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseDeleteOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.DeleteOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._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 cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseEchoRestTransport._BaseCancelOperation, EchoRestStub): + def __hash__(self): + return hash("EchoRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEchoRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseEchoRestTransport._BaseCancelOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.EchoClient.CancelOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Echo", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EchoRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EchoRestTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py new file mode 100644 index 000000000000..7c79f74ec328 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py @@ -0,0 +1,412 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 EchoTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.showcase_v1beta1.types import echo as gs_echo +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseEchoRestTransport(EchoTransport): + """Base REST backend transport for Echo. + + 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 = 'localhost:7469', + 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: 'localhost:7469'). + 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 _BaseBlock: + 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': '/v1beta1/echo:block', + 'body': '*', + }, + ] + return http_options + + class _BaseChat: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseCollect: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseEcho: + 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': '/v1beta1/echo:echo', + 'body': '*', + }, + ] + return http_options + + class _BaseEchoErrorDetails: + 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': '/v1beta1/echo:error-details', + 'body': '*', + }, + ] + return http_options + + class _BaseExpand: + 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': '/v1beta1/echo:expand', + 'body': '*', + }, + ] + return http_options + + class _BasePagedExpand: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/echo:pagedExpand', + 'body': '*', + }, + ] + return http_options + + class _BasePagedExpandLegacy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/echo:pagedExpandLegacy', + 'body': '*', + }, + ] + return http_options + + class _BasePagedExpandLegacyMapped: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/echo:pagedExpandLegacyMapped', + 'body': '*', + }, + ] + return http_options + + class _BaseWait: + 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': '/v1beta1/echo:wait', + 'body': '*', + }, + ] + return http_options + + 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': '/v1beta1/{name=projects/*}/locations', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=projects/*/locations/*}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=sequences/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=rooms/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=sequences/*}:getIamPolicy', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=sequences/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + pass + + 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': '/v1beta1/operations', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}:cancel', + }, + ] + return http_options + + pass + + +__all__=( + '_BaseEchoRestTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py new file mode 100644 index 000000000000..9b1629e41d24 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 IdentityClient +from .async_client import IdentityAsyncClient + +__all__ = ( + 'IdentityClient', + 'IdentityAsyncClient', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py new file mode 100644 index 000000000000..17a0c6e830dc --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py @@ -0,0 +1,1441 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import uuid + +from google.showcase_v1beta1 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 +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.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.showcase_v1beta1.services.identity import pagers +from google.showcase_v1beta1.types import identity +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from .transports.base import IdentityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import IdentityGrpcAsyncIOTransport +from .client import IdentityClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class IdentityAsyncClient: + """A simple identity service.""" + + _client: IdentityClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = IdentityClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IdentityClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = IdentityClient._DEFAULT_UNIVERSE + + user_path = staticmethod(IdentityClient.user_path) + parse_user_path = staticmethod(IdentityClient.parse_user_path) + common_billing_account_path = staticmethod(IdentityClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IdentityClient.parse_common_billing_account_path) + common_folder_path = staticmethod(IdentityClient.common_folder_path) + parse_common_folder_path = staticmethod(IdentityClient.parse_common_folder_path) + common_organization_path = staticmethod(IdentityClient.common_organization_path) + parse_common_organization_path = staticmethod(IdentityClient.parse_common_organization_path) + common_project_path = staticmethod(IdentityClient.common_project_path) + parse_common_project_path = staticmethod(IdentityClient.parse_common_project_path) + common_location_path = staticmethod(IdentityClient.common_location_path) + parse_common_location_path = staticmethod(IdentityClient.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: + IdentityAsyncClient: The constructed client. + """ + sa_info_func = ( + IdentityClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(IdentityAsyncClient, info, *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: + IdentityAsyncClient: The constructed client. + """ + sa_file_func = ( + IdentityClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(IdentityAsyncClient, filename, *args, **kwargs) + + 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 IdentityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> IdentityTransport: + """Returns the transport used by the client instance. + + Returns: + IdentityTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = IdentityClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, IdentityTransport, Callable[..., IdentityTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the identity 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,IdentityTransport,Callable[..., IdentityTransport]]]): + 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 IdentityTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = IdentityClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.showcase_v1beta1.IdentityAsyncClient`.", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.showcase.v1beta1.Identity", + "credentialsType": None, + } + ) + + async def create_user(self, + request: Optional[Union[identity.CreateUserRequest, dict]] = None, + *, + display_name: Optional[str] = None, + email: Optional[str] = None, + age: Optional[int] = None, + nickname: Optional[str] = None, + enable_notifications: Optional[bool] = None, + height_feet: Optional[float] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> identity.User: + r"""Creates a user. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_create_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateUserRequest( + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.CreateUserRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Identity\CreateUser + method. + display_name (:class:`str`): + The display_name of the user. + This corresponds to the ``user.display_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + email (:class:`str`): + The email address of the user. + This corresponds to the ``user.email`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + age (:class:`int`): + The age of the user in years. + This corresponds to the ``user.age`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + nickname (:class:`str`): + The nickname of the user. + + (-- aip.dev/not-precedent: An empty string is a valid + nickname. Ordinarily, proto3_optional should not be used + on a ``string`` field. --) + + This corresponds to the ``user.nickname`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enable_notifications (:class:`bool`): + Enables the receiving of notifications. The default is + true if unset. + + (-- aip.dev/not-precedent: The default for the feature + is true. Ordinarily, the default for a ``bool`` field + should be false. --) + + This corresponds to the ``user.enable_notifications`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + height_feet (:class:`float`): + The height of the user in feet. + This corresponds to the ``user.height_feet`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.User: + A user. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [display_name, email, age, nickname, enable_notifications, height_feet] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.CreateUserRequest): + request = identity.CreateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_name is not None: + request.user.display_name = display_name + if email is not None: + request.user.email = email + if age is not None: + request.user.age = age + if nickname is not None: + request.user.nickname = nickname + if enable_notifications is not None: + request.user.enable_notifications = enable_notifications + if height_feet is not None: + request.user.height_feet = height_feet + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user] + + # 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_user(self, + request: Optional[Union[identity.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> identity.User: + r"""Retrieves the User with the given uri. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_get_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.GetUserRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Identity\GetUser + method. + name (:class:`str`): + The resource name of the requested + user. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.User: + A user. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.GetUserRequest): + request = identity.GetUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_user] + + # Certain 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_user(self, + request: Optional[Union[identity.UpdateUserRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> identity.User: + r"""Updates a user. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_update_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.UpdateUserRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Identity\UpdateUser + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.User: + A user. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.UpdateUserRequest): + request = identity.UpdateUserRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.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_user(self, + request: Optional[Union[identity.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a user, their profile, and all of their + authored messages. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_delete_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.DeleteUserRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Identity\DeleteUser + method. + name (:class:`str`): + The resource name of the user to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.DeleteUserRequest): + request = identity.DeleteUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_users(self, + request: Optional[Union[identity.ListUsersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListUsersAsyncPager: + r"""Lists all users. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_list_users(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListUsersRequest( + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.ListUsersRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Identity\ListUsers + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.identity.pagers.ListUsersAsyncPager: + The response message for the + google.showcase.v1beta1.Identity\ListUsers + method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.ListUsersRequest): + request = identity.ListUsersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_users] + + # 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.ListUsersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "IdentityAsyncClient": + 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__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "IdentityAsyncClient", +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py new file mode 100644 index 000000000000..84a36f09cb88 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py @@ -0,0 +1,1872 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import uuid +import warnings + +from google.showcase_v1beta1 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 +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.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.showcase_v1beta1.services.identity import pagers +from google.showcase_v1beta1.types import identity +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from .transports.base import IdentityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import IdentityGrpcTransport +from .transports.grpc_asyncio import IdentityGrpcAsyncIOTransport +from .transports.rest import IdentityRestTransport + + +class IdentityClientMeta(type): + """Metaclass for the Identity 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[IdentityTransport]] + _transport_registry["grpc"] = IdentityGrpcTransport + _transport_registry["grpc_asyncio"] = IdentityGrpcAsyncIOTransport + _transport_registry["rest"] = IdentityRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[IdentityTransport]: + """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 IdentityClient(metaclass=IdentityClientMeta): + """A simple identity service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "localhost:7469" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "localhost:7469" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IdentityClient: 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: + IdentityClient: 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) -> IdentityTransport: + """Returns the transport used by the client instance. + + Returns: + IdentityTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def user_path(user: str,) -> str: + """Returns a fully-qualified user string.""" + return "users/{user}".format(user=user, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^users/(?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 = IdentityClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = IdentityClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + """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 = IdentityClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = IdentityClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = IdentityClient._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 = IdentityClient._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 + + @staticmethod + def _setup_request_id(request, field_name: str, is_proto3_optional: bool): + """Populate a UUID4 field in the request if it is not already set. + + Args: + request (Union[google.protobuf.message.Message, dict]): The request object. + field_name (str): The name of the field to populate. + is_proto3_optional (bool): Whether the field is proto3 optional. + """ + if isinstance(request, dict): + if is_proto3_optional: + if field_name not in request: + request[field_name] = str(uuid.uuid4()) + elif not request.get(field_name): + request[field_name] = str(uuid.uuid4()) + return + + if is_proto3_optional: + try: + # Pure protobuf messages + if not request.HasField(field_name): + setattr(request, field_name, str(uuid.uuid4())) + except (AttributeError, ValueError): + # Proto-plus messages or other objects + if field_name not in request: + setattr(request, field_name, str(uuid.uuid4())) + else: + if not getattr(request, field_name): + setattr(request, field_name, str(uuid.uuid4())) + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """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, IdentityTransport, Callable[..., IdentityTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the identity client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. 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,IdentityTransport,Callable[..., IdentityTransport]]]): + 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 IdentityTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = IdentityClient._read_environment_variables() + self._client_cert_source = IdentityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = IdentityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, IdentityTransport) + if transport_provided: + # transport is a IdentityTransport 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(IdentityTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + IdentityClient._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[IdentityTransport], Callable[..., IdentityTransport]] = ( + IdentityClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., IdentityTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.showcase_v1beta1.IdentityClient`.", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.showcase.v1beta1.Identity", + "credentialsType": None, + } + ) + + def create_user(self, + request: Optional[Union[identity.CreateUserRequest, dict]] = None, + *, + display_name: Optional[str] = None, + email: Optional[str] = None, + age: Optional[int] = None, + nickname: Optional[str] = None, + enable_notifications: Optional[bool] = None, + height_feet: Optional[float] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> identity.User: + r"""Creates a user. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_create_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateUserRequest( + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.CreateUserRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Identity\CreateUser + method. + display_name (str): + The display_name of the user. + This corresponds to the ``user.display_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + email (str): + The email address of the user. + This corresponds to the ``user.email`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + age (int): + The age of the user in years. + This corresponds to the ``user.age`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + nickname (str): + The nickname of the user. + + (-- aip.dev/not-precedent: An empty string is a valid + nickname. Ordinarily, proto3_optional should not be used + on a ``string`` field. --) + + This corresponds to the ``user.nickname`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enable_notifications (bool): + Enables the receiving of notifications. The default is + true if unset. + + (-- aip.dev/not-precedent: The default for the feature + is true. Ordinarily, the default for a ``bool`` field + should be false. --) + + This corresponds to the ``user.enable_notifications`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + height_feet (float): + The height of the user in feet. + This corresponds to the ``user.height_feet`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.User: + A user. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [display_name, email, age, nickname, enable_notifications, height_feet] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.CreateUserRequest): + request = identity.CreateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_name is not None: + request.user.display_name = display_name + if email is not None: + request.user.email = email + if age is not None: + request.user.age = age + if nickname is not None: + request.user.nickname = nickname + if enable_notifications is not None: + request.user.enable_notifications = enable_notifications + if height_feet is not None: + request.user.height_feet = height_feet + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user] + + # 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_user(self, + request: Optional[Union[identity.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> identity.User: + r"""Retrieves the User with the given uri. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_get_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.GetUserRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Identity\GetUser + method. + name (str): + The resource name of the requested + user. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.User: + A user. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.GetUserRequest): + request = identity.GetUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_user] + + # Certain 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_user(self, + request: Optional[Union[identity.UpdateUserRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> identity.User: + r"""Updates a user. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_update_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.UpdateUserRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Identity\UpdateUser + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.User: + A user. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.UpdateUserRequest): + request = identity.UpdateUserRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.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_user(self, + request: Optional[Union[identity.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a user, their profile, and all of their + authored messages. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_delete_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + Args: + request (Union[google.showcase_v1beta1.types.DeleteUserRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Identity\DeleteUser + method. + name (str): + The resource name of the user to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.DeleteUserRequest): + request = identity.DeleteUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_users(self, + request: Optional[Union[identity.ListUsersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListUsersPager: + r"""Lists all users. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_list_users(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListUsersRequest( + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.ListUsersRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Identity\ListUsers + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.identity.pagers.ListUsersPager: + The response message for the + google.showcase.v1beta1.Identity\ListUsers + method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, identity.ListUsersRequest): + request = identity.ListUsersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_users] + + # 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.ListUsersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "IdentityClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "IdentityClient", +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py new file mode 100644 index 000000000000..fc969a954c08 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1.types import identity + + +class ListUsersPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.ListUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.ListUsersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., identity.ListUsersResponse], + request: identity.ListUsersRequest, + response: identity.ListUsersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.ListUsersRequest): + The initial request object. + response (google.showcase_v1beta1.types.ListUsersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = identity.ListUsersRequest(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[identity.ListUsersResponse]: + 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[identity.User]: + for page in self.pages: + yield from page.users + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersAsyncPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.ListUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.ListUsersResponse` + attributes are available on the 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[identity.ListUsersResponse]], + request: identity.ListUsersRequest, + response: identity.ListUsersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.ListUsersRequest): + The initial request object. + response (google.showcase_v1beta1.types.ListUsersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = identity.ListUsersRequest(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[identity.ListUsersResponse]: + 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[identity.User]: + async def async_generator(): + async for page in self.pages: + for response in page.users: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst new file mode 100644 index 000000000000..180184c080a6 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``IdentityTransport`` is the ABC for all transports. + +- public child ``IdentityGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``IdentityGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseIdentityRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``IdentityRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py new file mode 100644 index 000000000000..c15bd7deb425 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 IdentityTransport +from .grpc import IdentityGrpcTransport +from .grpc_asyncio import IdentityGrpcAsyncIOTransport +from .rest import IdentityRestTransport +from .rest import IdentityRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IdentityTransport]] +_transport_registry['grpc'] = IdentityGrpcTransport +_transport_registry['grpc_asyncio'] = IdentityGrpcAsyncIOTransport +_transport_registry['rest'] = IdentityRestTransport + +__all__ = ( + 'IdentityTransport', + 'IdentityGrpcTransport', + 'IdentityGrpcAsyncIOTransport', + 'IdentityRestTransport', + 'IdentityRestInterceptor', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py new file mode 100644 index 000000000000..3d8c1973d646 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +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.showcase_v1beta1.types import identity +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class IdentityTransport(abc.ABC): + """Abstract transport class for Identity.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'localhost:7469' + + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_user: gapic_v1.method.wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.get_user: gapic_v1.method.wrap_method( + self.get_user, + default_retry=retries.Retry( + initial=0.2, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=5.0, + ), + default_timeout=5.0, + client_info=client_info, + ), + self.update_user: gapic_v1.method.wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: gapic_v1.method.wrap_method( + self.delete_user, + default_timeout=None, + client_info=client_info, + ), + self.list_users: gapic_v1.method.wrap_method( + self.list_users, + default_retry=retries.Retry( + initial=0.2, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=5.0, + ), + default_timeout=5.0, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + 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.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_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.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_user(self) -> Callable[ + [identity.CreateUserRequest], + Union[ + identity.User, + Awaitable[identity.User] + ]]: + raise NotImplementedError() + + @property + def get_user(self) -> Callable[ + [identity.GetUserRequest], + Union[ + identity.User, + Awaitable[identity.User] + ]]: + raise NotImplementedError() + + @property + def update_user(self) -> Callable[ + [identity.UpdateUserRequest], + Union[ + identity.User, + Awaitable[identity.User] + ]]: + raise NotImplementedError() + + @property + def delete_user(self) -> Callable[ + [identity.DeleteUserRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_users(self) -> Callable[ + [identity.ListUsersRequest], + Union[ + identity.ListUsersResponse, + Awaitable[identity.ListUsersResponse] + ]]: + 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__ = ( + 'IdentityTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py new file mode 100644 index 000000000000..332e019bd35c --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py @@ -0,0 +1,649 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.showcase_v1beta1.types import identity +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import IdentityTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class IdentityGrpcTransport(IdentityTransport): + """gRPC backend transport for Identity. + + A simple identity service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'localhost:7469', + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'localhost:7469', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_user(self) -> Callable[ + [identity.CreateUserRequest], + identity.User]: + r"""Return a callable for the create user method over gRPC. + + Creates a user. + + Returns: + Callable[[~.CreateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_user' not in self._stubs: + self._stubs['create_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/CreateUser', + request_serializer=identity.CreateUserRequest.serialize, + response_deserializer=identity.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def get_user(self) -> Callable[ + [identity.GetUserRequest], + identity.User]: + r"""Return a callable for the get user method over gRPC. + + Retrieves the User with the given uri. + + Returns: + Callable[[~.GetUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_user' not in self._stubs: + self._stubs['get_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/GetUser', + request_serializer=identity.GetUserRequest.serialize, + response_deserializer=identity.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def update_user(self) -> Callable[ + [identity.UpdateUserRequest], + identity.User]: + r"""Return a callable for the update user method over gRPC. + + Updates a user. + + Returns: + Callable[[~.UpdateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_user' not in self._stubs: + self._stubs['update_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/UpdateUser', + request_serializer=identity.UpdateUserRequest.serialize, + response_deserializer=identity.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [identity.DeleteUserRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a user, their profile, and all of their + authored messages. + + Returns: + Callable[[~.DeleteUserRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/DeleteUser', + request_serializer=identity.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + @property + def list_users(self) -> Callable[ + [identity.ListUsersRequest], + identity.ListUsersResponse]: + r"""Return a callable for the list users method over gRPC. + + Lists all users. + + Returns: + Callable[[~.ListUsersRequest], + ~.ListUsersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_users' not in self._stubs: + self._stubs['list_users'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/ListUsers', + request_serializer=identity.ListUsersRequest.serialize, + response_deserializer=identity.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'IdentityGrpcTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0b2ce53e949b --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py @@ -0,0 +1,755 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +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.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.showcase_v1beta1.types import identity +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import IdentityTransport, DEFAULT_CLIENT_INFO +from .grpc import IdentityGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class IdentityGrpcAsyncIOTransport(IdentityTransport): + """gRPC AsyncIO backend transport for Identity. + + A simple identity service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'localhost:7469', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'localhost:7469', + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_user(self) -> Callable[ + [identity.CreateUserRequest], + Awaitable[identity.User]]: + r"""Return a callable for the create user method over gRPC. + + Creates a user. + + Returns: + Callable[[~.CreateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_user' not in self._stubs: + self._stubs['create_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/CreateUser', + request_serializer=identity.CreateUserRequest.serialize, + response_deserializer=identity.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def get_user(self) -> Callable[ + [identity.GetUserRequest], + Awaitable[identity.User]]: + r"""Return a callable for the get user method over gRPC. + + Retrieves the User with the given uri. + + Returns: + Callable[[~.GetUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_user' not in self._stubs: + self._stubs['get_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/GetUser', + request_serializer=identity.GetUserRequest.serialize, + response_deserializer=identity.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def update_user(self) -> Callable[ + [identity.UpdateUserRequest], + Awaitable[identity.User]]: + r"""Return a callable for the update user method over gRPC. + + Updates a user. + + Returns: + Callable[[~.UpdateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_user' not in self._stubs: + self._stubs['update_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/UpdateUser', + request_serializer=identity.UpdateUserRequest.serialize, + response_deserializer=identity.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [identity.DeleteUserRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a user, their profile, and all of their + authored messages. + + Returns: + Callable[[~.DeleteUserRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/DeleteUser', + request_serializer=identity.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + @property + def list_users(self) -> Callable[ + [identity.ListUsersRequest], + Awaitable[identity.ListUsersResponse]]: + r"""Return a callable for the list users method over gRPC. + + Lists all users. + + Returns: + Callable[[~.ListUsersRequest], + Awaitable[~.ListUsersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_users' not in self._stubs: + self._stubs['list_users'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Identity/ListUsers', + request_serializer=identity.ListUsersRequest.serialize, + response_deserializer=identity.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_user: self._wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.get_user: self._wrap_method( + self.get_user, + default_retry=retries.AsyncRetry( + initial=0.2, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=5.0, + ), + default_timeout=5.0, + client_info=client_info, + ), + self.update_user: self._wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: self._wrap_method( + self.delete_user, + default_timeout=None, + client_info=client_info, + ), + self.list_users: self._wrap_method( + self.list_users, + default_retry=retries.AsyncRetry( + initial=0.2, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=5.0, + ), + default_timeout=5.0, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + 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.get_iam_policy: self._wrap_method( + self.get_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.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_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.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'IdentityGrpcAsyncIOTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py new file mode 100644 index 000000000000..d76096d100ab --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py @@ -0,0 +1,2270 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # 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.showcase_v1beta1 import _compat as rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +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 requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.showcase_v1beta1.types import identity +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseIdentityRestTransport +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 + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class IdentityRestInterceptor: + """Interceptor for Identity. + + 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 IdentityRestTransport. + + .. code-block:: python + class MyCustomIdentityInterceptor(IdentityRestInterceptor): + def pre_create_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user(self, response): + logging.log(f"Received response: {response}") + return response + + transport = IdentityRestTransport(interceptor=MyCustomIdentityInterceptor()) + client = IdentityClient(transport=transport) + + + """ + def pre_create_user(self, request: identity.CreateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity server. + """ + return request, metadata + + def post_create_user(self, response: identity.User) -> identity.User: + """Post-rpc interceptor for create_user + + DEPRECATED. Please use the `post_create_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Identity server but before + it is returned to user code. This `post_create_user` interceptor runs + before the `post_create_user_with_metadata` interceptor. + """ + return response + + def post_create_user_with_metadata(self, response: identity.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Identity server but before it is returned to user code. + + We recommend only using this `post_create_user_with_metadata` + interceptor in new development instead of the `post_create_user` interceptor. + When both interceptors are used, this `post_create_user_with_metadata` interceptor runs after the + `post_create_user` interceptor. The (possibly modified) response returned by + `post_create_user` will be passed to + `post_create_user_with_metadata`. + """ + return response, metadata + + def pre_delete_user(self, request: identity.DeleteUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity server. + """ + return request, metadata + + def pre_get_user(self, request: identity.GetUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity server. + """ + return request, metadata + + def post_get_user(self, response: identity.User) -> identity.User: + """Post-rpc interceptor for get_user + + DEPRECATED. Please use the `post_get_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Identity server but before + it is returned to user code. This `post_get_user` interceptor runs + before the `post_get_user_with_metadata` interceptor. + """ + return response + + def post_get_user_with_metadata(self, response: identity.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Identity server but before it is returned to user code. + + We recommend only using this `post_get_user_with_metadata` + interceptor in new development instead of the `post_get_user` interceptor. + When both interceptors are used, this `post_get_user_with_metadata` interceptor runs after the + `post_get_user` interceptor. The (possibly modified) response returned by + `post_get_user` will be passed to + `post_get_user_with_metadata`. + """ + return response, metadata + + def pre_list_users(self, request: identity.ListUsersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity server. + """ + return request, metadata + + def post_list_users(self, response: identity.ListUsersResponse) -> identity.ListUsersResponse: + """Post-rpc interceptor for list_users + + DEPRECATED. Please use the `post_list_users_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Identity server but before + it is returned to user code. This `post_list_users` interceptor runs + before the `post_list_users_with_metadata` interceptor. + """ + return response + + def post_list_users_with_metadata(self, response: identity.ListUsersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_users + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Identity server but before it is returned to user code. + + We recommend only using this `post_list_users_with_metadata` + interceptor in new development instead of the `post_list_users` interceptor. + When both interceptors are used, this `post_list_users_with_metadata` interceptor runs after the + `post_list_users` interceptor. The (possibly modified) response returned by + `post_list_users` will be passed to + `post_list_users_with_metadata`. + """ + return response, metadata + + def pre_update_user(self, request: identity.UpdateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity server. + """ + return request, metadata + + def post_update_user(self, response: identity.User) -> identity.User: + """Post-rpc interceptor for update_user + + DEPRECATED. Please use the `post_update_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Identity server but before + it is returned to user code. This `post_update_user` interceptor runs + before the `post_update_user_with_metadata` interceptor. + """ + return response + + def post_update_user_with_metadata(self, response: identity.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Identity server but before it is returned to user code. + + We recommend only using this `post_update_user_with_metadata` + interceptor in new development instead of the `post_update_user` interceptor. + When both interceptors are used, this `post_update_user_with_metadata` interceptor runs after the + `post_update_user` interceptor. The (possibly modified) response returned by + `post_update_user` will be passed to + `post_update_user_with_metadata`. + """ + return response, metadata + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Identity 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 Identity server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class IdentityRestStub: + _session: AuthorizedSession + _host: str + _interceptor: IdentityRestInterceptor + + +class IdentityRestTransport(_BaseIdentityRestTransport): + """REST backend synchronous transport for Identity. + + A simple identity service. + + This 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 = 'localhost:7469', + 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[IdentityRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[IdentityRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or IdentityRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateUser(_BaseIdentityRestTransport._BaseCreateUser, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.CreateUser") + + @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: identity.CreateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> identity.User: + r"""Call the create user method over HTTP. + + Args: + request (~.identity.CreateUserRequest): + The request object. The request message for the + google.showcase.v1beta1.Identity\CreateUser + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.identity.User: + A user. + """ + + http_options = _BaseIdentityRestTransport._BaseCreateUser._get_http_options() + request, metadata = self._interceptor.pre_create_user(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseCreateUser, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.CreateUser", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "CreateUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._CreateUser._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 = identity.User() + pb_resp = identity.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = identity.User.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityClient.create_user", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "CreateUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteUser(_BaseIdentityRestTransport._BaseDeleteUser, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.DeleteUser") + + @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: identity.DeleteUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user method over HTTP. + + Args: + request (~.identity.DeleteUserRequest): + The request object. The request message for the + google.showcase.v1beta1.Identity\DeleteUser + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseIdentityRestTransport._BaseDeleteUser._get_http_options() + request, metadata = self._interceptor.pre_delete_user(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseDeleteUser, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.DeleteUser", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "DeleteUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._DeleteUser._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetUser(_BaseIdentityRestTransport._BaseGetUser, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.GetUser") + + @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: identity.GetUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> identity.User: + r"""Call the get user method over HTTP. + + Args: + request (~.identity.GetUserRequest): + The request object. The request message for the + google.showcase.v1beta1.Identity\GetUser + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.identity.User: + A user. + """ + + http_options = _BaseIdentityRestTransport._BaseGetUser._get_http_options() + request, metadata = self._interceptor.pre_get_user(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseGetUser, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.GetUser", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._GetUser._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 = identity.User() + pb_resp = identity.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = identity.User.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityClient.get_user", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUsers(_BaseIdentityRestTransport._BaseListUsers, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.ListUsers") + + @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: identity.ListUsersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> identity.ListUsersResponse: + r"""Call the list users method over HTTP. + + Args: + request (~.identity.ListUsersRequest): + The request object. The request message for the + google.showcase.v1beta1.Identity\ListUsers + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.identity.ListUsersResponse: + The response message for the + google.showcase.v1beta1.Identity\ListUsers + method. + + """ + + http_options = _BaseIdentityRestTransport._BaseListUsers._get_http_options() + request, metadata = self._interceptor.pre_list_users(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseListUsers, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.ListUsers", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "ListUsers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._ListUsers._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 = identity.ListUsersResponse() + pb_resp = identity.ListUsersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_users(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_users_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = identity.ListUsersResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityClient.list_users", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "ListUsers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUser(_BaseIdentityRestTransport._BaseUpdateUser, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.UpdateUser") + + @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: identity.UpdateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> identity.User: + r"""Call the update user method over HTTP. + + Args: + request (~.identity.UpdateUserRequest): + The request object. The request message for the + google.showcase.v1beta1.Identity\UpdateUser + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.identity.User: + A user. + """ + + http_options = _BaseIdentityRestTransport._BaseUpdateUser._get_http_options() + request, metadata = self._interceptor.pre_update_user(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseUpdateUser, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.UpdateUser", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "UpdateUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._UpdateUser._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 = identity.User() + pb_resp = identity.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = identity.User.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityClient.update_user", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "UpdateUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_user(self) -> Callable[ + [identity.CreateUserRequest], + identity.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user(self) -> Callable[ + [identity.DeleteUserRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user(self) -> Callable[ + [identity.GetUserRequest], + identity.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_users(self) -> Callable[ + [identity.ListUsersRequest], + identity.ListUsersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user(self) -> Callable[ + [identity.UpdateUserRequest], + identity.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseIdentityRestTransport._BaseListLocations, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseIdentityRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseListLocations, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.ListLocations", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.ListLocations", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseIdentityRestTransport._BaseGetLocation, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseIdentityRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseGetLocation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.GetLocation", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.GetLocation", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseIdentityRestTransport._BaseSetIamPolicy, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseIdentityRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseSetIamPolicy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.SetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseIdentityRestTransport._BaseGetIamPolicy, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseIdentityRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseGetIamPolicy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.GetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseIdentityRestTransport._BaseTestIamPermissions, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseIdentityRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseTestIamPermissions, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.TestIamPermissions", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseIdentityRestTransport._BaseListOperations, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseIdentityRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseListOperations, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.ListOperations", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.ListOperations", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseIdentityRestTransport._BaseGetOperation, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseIdentityRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseGetOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.GetOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.IdentityAsyncClient.GetOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseIdentityRestTransport._BaseDeleteOperation, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseIdentityRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseDeleteOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.DeleteOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._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 cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseIdentityRestTransport._BaseCancelOperation, IdentityRestStub): + def __hash__(self): + return hash("IdentityRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseIdentityRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseIdentityRestTransport._BaseCancelOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.IdentityClient.CancelOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Identity", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = IdentityRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'IdentityRestTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py new file mode 100644 index 000000000000..01e9d7bd350f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 IdentityTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.showcase_v1beta1.types import identity +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseIdentityRestTransport(IdentityTransport): + """Base REST backend transport for Identity. + + 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 = 'localhost:7469', + 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: 'localhost:7469'). + 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 _BaseCreateUser: + 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': '/v1beta1/users', + 'body': '*', + }, + ] + return http_options + + class _BaseDeleteUser: + 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': '/v1beta1/{name=users/*}', + }, + ] + return http_options + + class _BaseGetUser: + 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': '/v1beta1/{name=users/*}', + }, + ] + return http_options + + class _BaseListUsers: + 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': '/v1beta1/users', + }, + ] + return http_options + + class _BaseUpdateUser: + 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': '/v1beta1/{user.name=users/*}', + 'body': 'user', + }, + ] + return http_options + + 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': '/v1beta1/{name=projects/*}/locations', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=projects/*/locations/*}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=sequences/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=rooms/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=sequences/*}:getIamPolicy', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=sequences/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + pass + + 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': '/v1beta1/operations', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}:cancel', + }, + ] + return http_options + + pass + + +__all__=( + '_BaseIdentityRestTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py new file mode 100644 index 000000000000..398d1b81e782 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 MessagingClient +from .async_client import MessagingAsyncClient + +__all__ = ( + 'MessagingClient', + 'MessagingAsyncClient', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py new file mode 100644 index 000000000000..807a1d5f52aa --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py @@ -0,0 +1,2367 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import uuid + +from google.showcase_v1beta1 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 +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.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.showcase_v1beta1.services.messaging import pagers +from google.showcase_v1beta1.types import messaging +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from .transports.base import MessagingTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import MessagingGrpcAsyncIOTransport +from .client import MessagingClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class MessagingAsyncClient: + """A simple messaging service that implements chat rooms and + profile posts. + This messaging service showcases the features that API clients + generated by gapic-generators implement. + """ + + _client: MessagingClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = MessagingClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = MessagingClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = MessagingClient._DEFAULT_UNIVERSE + + blurb_path = staticmethod(MessagingClient.blurb_path) + parse_blurb_path = staticmethod(MessagingClient.parse_blurb_path) + room_path = staticmethod(MessagingClient.room_path) + parse_room_path = staticmethod(MessagingClient.parse_room_path) + user_path = staticmethod(MessagingClient.user_path) + parse_user_path = staticmethod(MessagingClient.parse_user_path) + common_billing_account_path = staticmethod(MessagingClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(MessagingClient.parse_common_billing_account_path) + common_folder_path = staticmethod(MessagingClient.common_folder_path) + parse_common_folder_path = staticmethod(MessagingClient.parse_common_folder_path) + common_organization_path = staticmethod(MessagingClient.common_organization_path) + parse_common_organization_path = staticmethod(MessagingClient.parse_common_organization_path) + common_project_path = staticmethod(MessagingClient.common_project_path) + parse_common_project_path = staticmethod(MessagingClient.parse_common_project_path) + common_location_path = staticmethod(MessagingClient.common_location_path) + parse_common_location_path = staticmethod(MessagingClient.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: + MessagingAsyncClient: The constructed client. + """ + sa_info_func = ( + MessagingClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(MessagingAsyncClient, info, *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: + MessagingAsyncClient: The constructed client. + """ + sa_file_func = ( + MessagingClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(MessagingAsyncClient, filename, *args, **kwargs) + + 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 MessagingClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> MessagingTransport: + """Returns the transport used by the client instance. + + Returns: + MessagingTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = MessagingClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, MessagingTransport, Callable[..., MessagingTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the messaging 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,MessagingTransport,Callable[..., MessagingTransport]]]): + 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 MessagingTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = MessagingClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.showcase_v1beta1.MessagingAsyncClient`.", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.showcase.v1beta1.Messaging", + "credentialsType": None, + } + ) + + async def create_room(self, + request: Optional[Union[messaging.CreateRoomRequest, dict]] = None, + *, + display_name: Optional[str] = None, + description: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Room: + r"""Creates a room. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_create_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateRoomRequest( + ) + + # Make the request + response = await client.create_room(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.CreateRoomRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\CreateRoom + method. + display_name (:class:`str`): + The human readable name of the chat + room. + + This corresponds to the ``room.display_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + description (:class:`str`): + The description of the chat room. + This corresponds to the ``room.description`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Room: + A chat room. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [display_name, description] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.CreateRoomRequest): + request = messaging.CreateRoomRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_name is not None: + request.room.display_name = display_name + if description is not None: + request.room.description = description + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_room] + + # 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_room(self, + request: Optional[Union[messaging.GetRoomRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Room: + r"""Retrieves the Room with the given resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_get_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetRoomRequest( + name="name_value", + ) + + # Make the request + response = await client.get_room(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.GetRoomRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\GetRoom + method. + name (:class:`str`): + The resource name of the requested + room. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Room: + A chat room. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.GetRoomRequest): + request = messaging.GetRoomRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_room] + + # Certain 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_room(self, + request: Optional[Union[messaging.UpdateRoomRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Room: + r"""Updates a room. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_update_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateRoomRequest( + ) + + # Make the request + response = await client.update_room(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.UpdateRoomRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\UpdateRoom + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Room: + A chat room. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.UpdateRoomRequest): + request = messaging.UpdateRoomRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_room] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("room.name", request.room.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_room(self, + request: Optional[Union[messaging.DeleteRoomRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a room and all of its blurbs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_delete_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteRoomRequest( + name="name_value", + ) + + # Make the request + await client.delete_room(request=request) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.DeleteRoomRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\DeleteRoom + method. + name (:class:`str`): + The resource name of the requested + room. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.DeleteRoomRequest): + request = messaging.DeleteRoomRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_room] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_rooms(self, + request: Optional[Union[messaging.ListRoomsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRoomsAsyncPager: + r"""Lists all chat rooms. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_list_rooms(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListRoomsRequest( + ) + + # Make the request + page_result = client.list_rooms(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.ListRoomsRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\ListRooms + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.messaging.pagers.ListRoomsAsyncPager: + The response message for the + google.showcase.v1beta1.Messaging\ListRooms + method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.ListRoomsRequest): + request = messaging.ListRoomsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_rooms] + + # 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.ListRoomsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_blurb(self, + request: Optional[Union[messaging.CreateBlurbRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[str] = None, + text: Optional[str] = None, + image: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Blurb: + r"""Creates a blurb. If the parent is a room, the blurb + is understood to be a message in that room. If the + parent is a profile, the blurb is understood to be a + post on the profile. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_create_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_blurb(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.CreateBlurbRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\CreateBlurb + method. + parent (:class:`str`): + The resource name of the chat room or + user profile that this blurb will be + tied to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`str`): + The resource name of the blurb's + author. + + This corresponds to the ``blurb.user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + text (:class:`str`): + The textual content of this blurb. + This corresponds to the ``blurb.text`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + image (:class:`bytes`): + The image content of this blurb. + This corresponds to the ``blurb.image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, user, text, image] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.CreateBlurbRequest): + request = messaging.CreateBlurbRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.blurb.user = user + if text is not None: + request.blurb.text = text + if image is not None: + request.blurb.image = image + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_blurb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_blurb(self, + request: Optional[Union[messaging.GetBlurbRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Blurb: + r"""Retrieves the Blurb with the given resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_get_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetBlurbRequest( + name="name_value", + ) + + # Make the request + response = await client.get_blurb(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.GetBlurbRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\GetBlurb + method. + name (:class:`str`): + The resource name of the requested + blurb. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.GetBlurbRequest): + request = messaging.GetBlurbRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_blurb] + + # Certain 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_blurb(self, + request: Optional[Union[messaging.UpdateBlurbRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Blurb: + r"""Updates a blurb. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_update_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateBlurbRequest( + ) + + # Make the request + response = await client.update_blurb(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.UpdateBlurbRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\UpdateBlurb + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.UpdateBlurbRequest): + request = messaging.UpdateBlurbRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_blurb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("blurb.name", request.blurb.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_blurb(self, + request: Optional[Union[messaging.DeleteBlurbRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a blurb. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_delete_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteBlurbRequest( + name="name_value", + ) + + # Make the request + await client.delete_blurb(request=request) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.DeleteBlurbRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\DeleteBlurb + method. + name (:class:`str`): + The resource name of the requested + blurb. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.DeleteBlurbRequest): + request = messaging.DeleteBlurbRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_blurb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_blurbs(self, + request: Optional[Union[messaging.ListBlurbsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBlurbsAsyncPager: + r"""Lists blurbs for a specific chat room or user profile + depending on the parent resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_list_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListBlurbsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_blurbs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.ListBlurbsRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\ListBlurbs + method. + parent (:class:`str`): + The resource name of the requested + room or profile whos blurbs to list. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.messaging.pagers.ListBlurbsAsyncPager: + The response message for the + google.showcase.v1beta1.Messaging\ListBlurbs + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.ListBlurbsRequest): + request = messaging.ListBlurbsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_blurbs] + + # Certain 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.ListBlurbsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_blurbs(self, + request: Optional[Union[messaging.SearchBlurbsRequest, dict]] = None, + *, + parent: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""This method searches through all blurbs across all + rooms and profiles for blurbs containing to words found + in the query. Only posts that contain an exact match of + a queried word will be returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_search_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.SearchBlurbsRequest( + query="query_value", + ) + + # Make the request + operation = await client.search_blurbs(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.SearchBlurbsRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\SearchBlurbs + method. + parent (:class:`str`): + The rooms or profiles to search. If unset, + ``SearchBlurbs`` will search all rooms and all profiles. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + The query used to search for blurbs + containing to words of this string. Only + posts that contain an exact match of a + queried word will be returned. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.showcase_v1beta1.types.SearchBlurbsResponse` The operation response message for the + google.showcase.v1beta1.MessagingSearchBlurbs method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, query] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.SearchBlurbsRequest): + request = messaging.SearchBlurbsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_blurbs] + + # Certain 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, + messaging.SearchBlurbsResponse, + metadata_type=messaging.SearchBlurbsMetadata, + ) + + # Done; return the response. + return response + + def stream_blurbs(self, + request: Optional[Union[messaging.StreamBlurbsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[messaging.StreamBlurbsResponse]]: + r"""This returns a stream that emits the blurbs that are + created for a particular chat room or user profile. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_stream_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.StreamBlurbsRequest( + name="name_value", + ) + + # Make the request + stream = await client.stream_blurbs(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.showcase_v1beta1.types.StreamBlurbsRequest, dict]]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: + The response message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.StreamBlurbsRequest): + request = messaging.StreamBlurbsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.stream_blurbs] + + # Certain 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 = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def send_blurbs(self, + requests: Optional[AsyncIterator[messaging.CreateBlurbRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.SendBlurbsResponse: + r"""This is a stream to create multiple blurbs. If an + invalid blurb is requested to be created, the stream + will close with an error. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_send_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.CreateBlurbRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = await client.send_blurbs(requests=request_generator()) + + # Handle the response + print(response) + + Args: + requests (AsyncIterator[`google.showcase_v1beta1.types.CreateBlurbRequest`]): + The request object AsyncIterator. The request message for the + google.showcase.v1beta1.Messaging\CreateBlurb + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.SendBlurbsResponse: + The response message for the + google.showcase.v1beta1.Messaging\SendBlurbs + method. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.send_blurbs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def connect(self, + requests: Optional[AsyncIterator[messaging.ConnectRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[messaging.StreamBlurbsResponse]]: + r"""This method starts a bidirectional stream that + receives all blurbs that are being created after the + stream has started and sends requests to create blurbs. + If an invalid blurb is requested to be created, the + stream will close with an error. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + async def sample_connect(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ConnectRequest( + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.ConnectRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.connect(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.showcase_v1beta1.types.ConnectRequest`]): + The request object AsyncIterator. The request message for the + google.showcase.v1beta1.Messaging\Connect + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: + The response message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.connect] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "MessagingAsyncClient": + 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__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "MessagingAsyncClient", +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py new file mode 100644 index 000000000000..bfa9df3e0ffd --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py @@ -0,0 +1,2811 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +import uuid +import warnings + +from google.showcase_v1beta1 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 +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.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.showcase_v1beta1.services.messaging import pagers +from google.showcase_v1beta1.types import messaging +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from .transports.base import MessagingTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import MessagingGrpcTransport +from .transports.grpc_asyncio import MessagingGrpcAsyncIOTransport +from .transports.rest import MessagingRestTransport + + +class MessagingClientMeta(type): + """Metaclass for the Messaging 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[MessagingTransport]] + _transport_registry["grpc"] = MessagingGrpcTransport + _transport_registry["grpc_asyncio"] = MessagingGrpcAsyncIOTransport + _transport_registry["rest"] = MessagingRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[MessagingTransport]: + """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 MessagingClient(metaclass=MessagingClientMeta): + """A simple messaging service that implements chat rooms and + profile posts. + This messaging service showcases the features that API clients + generated by gapic-generators implement. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "localhost:7469" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "localhost:7469" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + MessagingClient: 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: + MessagingClient: 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) -> MessagingTransport: + """Returns the transport used by the client instance. + + Returns: + MessagingTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def blurb_path(user: str,legacy_user: str,blurb: str,) -> str: + """Returns a fully-qualified blurb string.""" + return "users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}".format(user=user, legacy_user=legacy_user, blurb=blurb, ) + + @staticmethod + def parse_blurb_path(path: str) -> Dict[str,str]: + """Parses a blurb path into its component segments.""" + m = re.match(r"^users/(?P.+?)/profile/blurbs/legacy/(?P.+?)~(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def room_path(room: str,) -> str: + """Returns a fully-qualified room string.""" + return "rooms/{room}".format(room=room, ) + + @staticmethod + def parse_room_path(path: str) -> Dict[str,str]: + """Parses a room path into its component segments.""" + m = re.match(r"^rooms/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(user: str,) -> str: + """Returns a fully-qualified user string.""" + return "users/{user}".format(user=user, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^users/(?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 = MessagingClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = MessagingClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + """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 = MessagingClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = MessagingClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = MessagingClient._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 = MessagingClient._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 + + @staticmethod + def _setup_request_id(request, field_name: str, is_proto3_optional: bool): + """Populate a UUID4 field in the request if it is not already set. + + Args: + request (Union[google.protobuf.message.Message, dict]): The request object. + field_name (str): The name of the field to populate. + is_proto3_optional (bool): Whether the field is proto3 optional. + """ + if isinstance(request, dict): + if is_proto3_optional: + if field_name not in request: + request[field_name] = str(uuid.uuid4()) + elif not request.get(field_name): + request[field_name] = str(uuid.uuid4()) + return + + if is_proto3_optional: + try: + # Pure protobuf messages + if not request.HasField(field_name): + setattr(request, field_name, str(uuid.uuid4())) + except (AttributeError, ValueError): + # Proto-plus messages or other objects + if field_name not in request: + setattr(request, field_name, str(uuid.uuid4())) + else: + if not getattr(request, field_name): + setattr(request, field_name, str(uuid.uuid4())) + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """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, MessagingTransport, Callable[..., MessagingTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the messaging client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. 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,MessagingTransport,Callable[..., MessagingTransport]]]): + 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 MessagingTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = MessagingClient._read_environment_variables() + self._client_cert_source = MessagingClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = MessagingClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, MessagingTransport) + if transport_provided: + # transport is a MessagingTransport 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(MessagingTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + MessagingClient._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[MessagingTransport], Callable[..., MessagingTransport]] = ( + MessagingClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., MessagingTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.showcase_v1beta1.MessagingClient`.", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.showcase.v1beta1.Messaging", + "credentialsType": None, + } + ) + + def create_room(self, + request: Optional[Union[messaging.CreateRoomRequest, dict]] = None, + *, + display_name: Optional[str] = None, + description: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Room: + r"""Creates a room. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_create_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateRoomRequest( + ) + + # Make the request + response = client.create_room(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.CreateRoomRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\CreateRoom + method. + display_name (str): + The human readable name of the chat + room. + + This corresponds to the ``room.display_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + description (str): + The description of the chat room. + This corresponds to the ``room.description`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Room: + A chat room. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [display_name, description] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.CreateRoomRequest): + request = messaging.CreateRoomRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_name is not None: + request.room.display_name = display_name + if description is not None: + request.room.description = description + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_room] + + # 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_room(self, + request: Optional[Union[messaging.GetRoomRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Room: + r"""Retrieves the Room with the given resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_get_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetRoomRequest( + name="name_value", + ) + + # Make the request + response = client.get_room(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.GetRoomRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\GetRoom + method. + name (str): + The resource name of the requested + room. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Room: + A chat room. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.GetRoomRequest): + request = messaging.GetRoomRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_room] + + # Certain 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_room(self, + request: Optional[Union[messaging.UpdateRoomRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Room: + r"""Updates a room. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_update_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateRoomRequest( + ) + + # Make the request + response = client.update_room(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.UpdateRoomRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\UpdateRoom + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Room: + A chat room. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.UpdateRoomRequest): + request = messaging.UpdateRoomRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_room] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("room.name", request.room.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_room(self, + request: Optional[Union[messaging.DeleteRoomRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a room and all of its blurbs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_delete_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteRoomRequest( + name="name_value", + ) + + # Make the request + client.delete_room(request=request) + + Args: + request (Union[google.showcase_v1beta1.types.DeleteRoomRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\DeleteRoom + method. + name (str): + The resource name of the requested + room. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.DeleteRoomRequest): + request = messaging.DeleteRoomRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_room] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_rooms(self, + request: Optional[Union[messaging.ListRoomsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRoomsPager: + r"""Lists all chat rooms. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_list_rooms(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListRoomsRequest( + ) + + # Make the request + page_result = client.list_rooms(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.ListRoomsRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\ListRooms + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.messaging.pagers.ListRoomsPager: + The response message for the + google.showcase.v1beta1.Messaging\ListRooms + method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.ListRoomsRequest): + request = messaging.ListRoomsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_rooms] + + # 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.ListRoomsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_blurb(self, + request: Optional[Union[messaging.CreateBlurbRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[str] = None, + text: Optional[str] = None, + image: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Blurb: + r"""Creates a blurb. If the parent is a room, the blurb + is understood to be a message in that room. If the + parent is a profile, the blurb is understood to be a + post on the profile. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_create_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_blurb(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.CreateBlurbRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\CreateBlurb + method. + parent (str): + The resource name of the chat room or + user profile that this blurb will be + tied to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (str): + The resource name of the blurb's + author. + + This corresponds to the ``blurb.user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + text (str): + The textual content of this blurb. + This corresponds to the ``blurb.text`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + image (bytes): + The image content of this blurb. + This corresponds to the ``blurb.image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, user, text, image] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.CreateBlurbRequest): + request = messaging.CreateBlurbRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.blurb.user = user + if text is not None: + request.blurb.text = text + if image is not None: + request.blurb.image = image + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_blurb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_blurb(self, + request: Optional[Union[messaging.GetBlurbRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Blurb: + r"""Retrieves the Blurb with the given resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_get_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetBlurbRequest( + name="name_value", + ) + + # Make the request + response = client.get_blurb(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.GetBlurbRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\GetBlurb + method. + name (str): + The resource name of the requested + blurb. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.GetBlurbRequest): + request = messaging.GetBlurbRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_blurb] + + # Certain 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_blurb(self, + request: Optional[Union[messaging.UpdateBlurbRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.Blurb: + r"""Updates a blurb. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_update_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateBlurbRequest( + ) + + # Make the request + response = client.update_blurb(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.UpdateBlurbRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\UpdateBlurb + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.UpdateBlurbRequest): + request = messaging.UpdateBlurbRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_blurb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("blurb.name", request.blurb.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_blurb(self, + request: Optional[Union[messaging.DeleteBlurbRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a blurb. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_delete_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteBlurbRequest( + name="name_value", + ) + + # Make the request + client.delete_blurb(request=request) + + Args: + request (Union[google.showcase_v1beta1.types.DeleteBlurbRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\DeleteBlurb + method. + name (str): + The resource name of the requested + blurb. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.DeleteBlurbRequest): + request = messaging.DeleteBlurbRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_blurb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_blurbs(self, + request: Optional[Union[messaging.ListBlurbsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBlurbsPager: + r"""Lists blurbs for a specific chat room or user profile + depending on the parent resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_list_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListBlurbsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_blurbs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.ListBlurbsRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\ListBlurbs + method. + parent (str): + The resource name of the requested + room or profile whos blurbs to list. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.services.messaging.pagers.ListBlurbsPager: + The response message for the + google.showcase.v1beta1.Messaging\ListBlurbs + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.ListBlurbsRequest): + request = messaging.ListBlurbsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_blurbs] + + # Certain 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.ListBlurbsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_blurbs(self, + request: Optional[Union[messaging.SearchBlurbsRequest, dict]] = None, + *, + parent: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""This method searches through all blurbs across all + rooms and profiles for blurbs containing to words found + in the query. Only posts that contain an exact match of + a queried word will be returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_search_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.SearchBlurbsRequest( + query="query_value", + ) + + # Make the request + operation = client.search_blurbs(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.SearchBlurbsRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\SearchBlurbs + method. + parent (str): + The rooms or profiles to search. If unset, + ``SearchBlurbs`` will search all rooms and all profiles. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + The query used to search for blurbs + containing to words of this string. Only + posts that contain an exact match of a + queried word will be returned. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.showcase_v1beta1.types.SearchBlurbsResponse` The operation response message for the + google.showcase.v1beta1.MessagingSearchBlurbs method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, query] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.SearchBlurbsRequest): + request = messaging.SearchBlurbsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_blurbs] + + # Certain 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, + messaging.SearchBlurbsResponse, + metadata_type=messaging.SearchBlurbsMetadata, + ) + + # Done; return the response. + return response + + def stream_blurbs(self, + request: Optional[Union[messaging.StreamBlurbsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[messaging.StreamBlurbsResponse]: + r"""This returns a stream that emits the blurbs that are + created for a particular chat room or user profile. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_stream_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.StreamBlurbsRequest( + name="name_value", + ) + + # Make the request + stream = client.stream_blurbs(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.showcase_v1beta1.types.StreamBlurbsRequest, dict]): + The request object. The request message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: + The response message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, messaging.StreamBlurbsRequest): + request = messaging.StreamBlurbsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stream_blurbs] + + # Certain 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 send_blurbs(self, + requests: Optional[Iterator[messaging.CreateBlurbRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> messaging.SendBlurbsResponse: + r"""This is a stream to create multiple blurbs. If an + invalid blurb is requested to be created, the stream + will close with an error. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_send_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.CreateBlurbRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = client.send_blurbs(requests=request_generator()) + + # Handle the response + print(response) + + Args: + requests (Iterator[google.showcase_v1beta1.types.CreateBlurbRequest]): + The request object iterator. The request message for the + google.showcase.v1beta1.Messaging\CreateBlurb + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.showcase_v1beta1.types.SendBlurbsResponse: + The response message for the + google.showcase.v1beta1.Messaging\SendBlurbs + method. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_blurbs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def connect(self, + requests: Optional[Iterator[messaging.ConnectRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[messaging.StreamBlurbsResponse]: + r"""This method starts a bidirectional stream that + receives all blurbs that are being created after the + stream has started and sends requests to create blurbs. + If an invalid blurb is requested to be created, the + stream will close with an error. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import showcase_v1beta1 + + def sample_connect(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ConnectRequest( + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.ConnectRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.connect(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.showcase_v1beta1.types.ConnectRequest]): + The request object iterator. The request message for the + google.showcase.v1beta1.Messaging\Connect + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: + The response message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.connect] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "MessagingClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = 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_pb.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "MessagingClient", +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py new file mode 100644 index 000000000000..711bbecfdb1d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1.types import messaging + + +class ListRoomsPager: + """A pager for iterating through ``list_rooms`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.ListRoomsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``rooms`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRooms`` requests and continue to iterate + through the ``rooms`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.ListRoomsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., messaging.ListRoomsResponse], + request: messaging.ListRoomsRequest, + response: messaging.ListRoomsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.ListRoomsRequest): + The initial request object. + response (google.showcase_v1beta1.types.ListRoomsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = messaging.ListRoomsRequest(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[messaging.ListRoomsResponse]: + 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[messaging.Room]: + for page in self.pages: + yield from page.rooms + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRoomsAsyncPager: + """A pager for iterating through ``list_rooms`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.ListRoomsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``rooms`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRooms`` requests and continue to iterate + through the ``rooms`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.ListRoomsResponse` + attributes are available on the 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[messaging.ListRoomsResponse]], + request: messaging.ListRoomsRequest, + response: messaging.ListRoomsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.ListRoomsRequest): + The initial request object. + response (google.showcase_v1beta1.types.ListRoomsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = messaging.ListRoomsRequest(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[messaging.ListRoomsResponse]: + 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[messaging.Room]: + async def async_generator(): + async for page in self.pages: + for response in page.rooms: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBlurbsPager: + """A pager for iterating through ``list_blurbs`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.ListBlurbsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``blurbs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBlurbs`` requests and continue to iterate + through the ``blurbs`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.ListBlurbsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., messaging.ListBlurbsResponse], + request: messaging.ListBlurbsRequest, + response: messaging.ListBlurbsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.ListBlurbsRequest): + The initial request object. + response (google.showcase_v1beta1.types.ListBlurbsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = messaging.ListBlurbsRequest(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[messaging.ListBlurbsResponse]: + 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[messaging.Blurb]: + for page in self.pages: + yield from page.blurbs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBlurbsAsyncPager: + """A pager for iterating through ``list_blurbs`` requests. + + This class thinly wraps an initial + :class:`google.showcase_v1beta1.types.ListBlurbsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``blurbs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBlurbs`` requests and continue to iterate + through the ``blurbs`` field on the + corresponding responses. + + All the usual :class:`google.showcase_v1beta1.types.ListBlurbsResponse` + attributes are available on the 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[messaging.ListBlurbsResponse]], + request: messaging.ListBlurbsRequest, + response: messaging.ListBlurbsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.showcase_v1beta1.types.ListBlurbsRequest): + The initial request object. + response (google.showcase_v1beta1.types.ListBlurbsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = messaging.ListBlurbsRequest(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[messaging.ListBlurbsResponse]: + 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[messaging.Blurb]: + async def async_generator(): + async for page in self.pages: + for response in page.blurbs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst new file mode 100644 index 000000000000..1d6729e40638 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``MessagingTransport`` is the ABC for all transports. + +- public child ``MessagingGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``MessagingGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseMessagingRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``MessagingRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py new file mode 100644 index 000000000000..cffcf10c086d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 MessagingTransport +from .grpc import MessagingGrpcTransport +from .grpc_asyncio import MessagingGrpcAsyncIOTransport +from .rest import MessagingRestTransport +from .rest import MessagingRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[MessagingTransport]] +_transport_registry['grpc'] = MessagingGrpcTransport +_transport_registry['grpc_asyncio'] = MessagingGrpcAsyncIOTransport +_transport_registry['rest'] = MessagingRestTransport + +__all__ = ( + 'MessagingTransport', + 'MessagingGrpcTransport', + 'MessagingGrpcAsyncIOTransport', + 'MessagingRestTransport', + 'MessagingRestInterceptor', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py new file mode 100644 index 000000000000..56895799a573 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py @@ -0,0 +1,542 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.showcase_v1beta1 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 +import google.protobuf + +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.showcase_v1beta1.types import messaging +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class MessagingTransport(abc.ABC): + """Abstract transport class for Messaging.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'localhost:7469' + + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_room: gapic_v1.method.wrap_method( + self.create_room, + default_timeout=None, + client_info=client_info, + ), + self.get_room: gapic_v1.method.wrap_method( + self.get_room, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.update_room: gapic_v1.method.wrap_method( + self.update_room, + default_timeout=None, + client_info=client_info, + ), + self.delete_room: gapic_v1.method.wrap_method( + self.delete_room, + default_timeout=None, + client_info=client_info, + ), + self.list_rooms: gapic_v1.method.wrap_method( + self.list_rooms, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.create_blurb: gapic_v1.method.wrap_method( + self.create_blurb, + default_timeout=None, + client_info=client_info, + ), + self.get_blurb: gapic_v1.method.wrap_method( + self.get_blurb, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.update_blurb: gapic_v1.method.wrap_method( + self.update_blurb, + default_timeout=None, + client_info=client_info, + ), + self.delete_blurb: gapic_v1.method.wrap_method( + self.delete_blurb, + default_timeout=None, + client_info=client_info, + ), + self.list_blurbs: gapic_v1.method.wrap_method( + self.list_blurbs, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.search_blurbs: gapic_v1.method.wrap_method( + self.search_blurbs, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.stream_blurbs: gapic_v1.method.wrap_method( + self.stream_blurbs, + default_timeout=None, + client_info=client_info, + ), + self.send_blurbs: gapic_v1.method.wrap_method( + self.send_blurbs, + default_timeout=None, + client_info=client_info, + ), + self.connect: gapic_v1.method.wrap_method( + self.connect, + default_retry=retries.Retry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + 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.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_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.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_room(self) -> Callable[ + [messaging.CreateRoomRequest], + Union[ + messaging.Room, + Awaitable[messaging.Room] + ]]: + raise NotImplementedError() + + @property + def get_room(self) -> Callable[ + [messaging.GetRoomRequest], + Union[ + messaging.Room, + Awaitable[messaging.Room] + ]]: + raise NotImplementedError() + + @property + def update_room(self) -> Callable[ + [messaging.UpdateRoomRequest], + Union[ + messaging.Room, + Awaitable[messaging.Room] + ]]: + raise NotImplementedError() + + @property + def delete_room(self) -> Callable[ + [messaging.DeleteRoomRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_rooms(self) -> Callable[ + [messaging.ListRoomsRequest], + Union[ + messaging.ListRoomsResponse, + Awaitable[messaging.ListRoomsResponse] + ]]: + raise NotImplementedError() + + @property + def create_blurb(self) -> Callable[ + [messaging.CreateBlurbRequest], + Union[ + messaging.Blurb, + Awaitable[messaging.Blurb] + ]]: + raise NotImplementedError() + + @property + def get_blurb(self) -> Callable[ + [messaging.GetBlurbRequest], + Union[ + messaging.Blurb, + Awaitable[messaging.Blurb] + ]]: + raise NotImplementedError() + + @property + def update_blurb(self) -> Callable[ + [messaging.UpdateBlurbRequest], + Union[ + messaging.Blurb, + Awaitable[messaging.Blurb] + ]]: + raise NotImplementedError() + + @property + def delete_blurb(self) -> Callable[ + [messaging.DeleteBlurbRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_blurbs(self) -> Callable[ + [messaging.ListBlurbsRequest], + Union[ + messaging.ListBlurbsResponse, + Awaitable[messaging.ListBlurbsResponse] + ]]: + raise NotImplementedError() + + @property + def search_blurbs(self) -> Callable[ + [messaging.SearchBlurbsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def stream_blurbs(self) -> Callable[ + [messaging.StreamBlurbsRequest], + Union[ + messaging.StreamBlurbsResponse, + Awaitable[messaging.StreamBlurbsResponse] + ]]: + raise NotImplementedError() + + @property + def send_blurbs(self) -> Callable[ + [messaging.CreateBlurbRequest], + Union[ + messaging.SendBlurbsResponse, + Awaitable[messaging.SendBlurbsResponse] + ]]: + raise NotImplementedError() + + @property + def connect(self) -> Callable[ + [messaging.ConnectRequest], + Union[ + messaging.StreamBlurbsResponse, + Awaitable[messaging.StreamBlurbsResponse] + ]]: + 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__ = ( + 'MessagingTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py new file mode 100644 index 000000000000..4d747c43ed51 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py @@ -0,0 +1,917 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.showcase_v1beta1.types import messaging +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import MessagingTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MessagingGrpcTransport(MessagingTransport): + """gRPC backend transport for Messaging. + + A simple messaging service that implements chat rooms and + profile posts. + This messaging service showcases the features that API clients + generated by gapic-generators implement. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'localhost:7469', + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'localhost:7469', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_room(self) -> Callable[ + [messaging.CreateRoomRequest], + messaging.Room]: + r"""Return a callable for the create room method over gRPC. + + Creates a room. + + Returns: + Callable[[~.CreateRoomRequest], + ~.Room]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_room' not in self._stubs: + self._stubs['create_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/CreateRoom', + request_serializer=messaging.CreateRoomRequest.serialize, + response_deserializer=messaging.Room.deserialize, + ) + return self._stubs['create_room'] + + @property + def get_room(self) -> Callable[ + [messaging.GetRoomRequest], + messaging.Room]: + r"""Return a callable for the get room method over gRPC. + + Retrieves the Room with the given resource name. + + Returns: + Callable[[~.GetRoomRequest], + ~.Room]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_room' not in self._stubs: + self._stubs['get_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/GetRoom', + request_serializer=messaging.GetRoomRequest.serialize, + response_deserializer=messaging.Room.deserialize, + ) + return self._stubs['get_room'] + + @property + def update_room(self) -> Callable[ + [messaging.UpdateRoomRequest], + messaging.Room]: + r"""Return a callable for the update room method over gRPC. + + Updates a room. + + Returns: + Callable[[~.UpdateRoomRequest], + ~.Room]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_room' not in self._stubs: + self._stubs['update_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/UpdateRoom', + request_serializer=messaging.UpdateRoomRequest.serialize, + response_deserializer=messaging.Room.deserialize, + ) + return self._stubs['update_room'] + + @property + def delete_room(self) -> Callable[ + [messaging.DeleteRoomRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete room method over gRPC. + + Deletes a room and all of its blurbs. + + Returns: + Callable[[~.DeleteRoomRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_room' not in self._stubs: + self._stubs['delete_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/DeleteRoom', + request_serializer=messaging.DeleteRoomRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_room'] + + @property + def list_rooms(self) -> Callable[ + [messaging.ListRoomsRequest], + messaging.ListRoomsResponse]: + r"""Return a callable for the list rooms method over gRPC. + + Lists all chat rooms. + + Returns: + Callable[[~.ListRoomsRequest], + ~.ListRoomsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_rooms' not in self._stubs: + self._stubs['list_rooms'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/ListRooms', + request_serializer=messaging.ListRoomsRequest.serialize, + response_deserializer=messaging.ListRoomsResponse.deserialize, + ) + return self._stubs['list_rooms'] + + @property + def create_blurb(self) -> Callable[ + [messaging.CreateBlurbRequest], + messaging.Blurb]: + r"""Return a callable for the create blurb method over gRPC. + + Creates a blurb. If the parent is a room, the blurb + is understood to be a message in that room. If the + parent is a profile, the blurb is understood to be a + post on the profile. + + Returns: + Callable[[~.CreateBlurbRequest], + ~.Blurb]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_blurb' not in self._stubs: + self._stubs['create_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/CreateBlurb', + request_serializer=messaging.CreateBlurbRequest.serialize, + response_deserializer=messaging.Blurb.deserialize, + ) + return self._stubs['create_blurb'] + + @property + def get_blurb(self) -> Callable[ + [messaging.GetBlurbRequest], + messaging.Blurb]: + r"""Return a callable for the get blurb method over gRPC. + + Retrieves the Blurb with the given resource name. + + Returns: + Callable[[~.GetBlurbRequest], + ~.Blurb]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_blurb' not in self._stubs: + self._stubs['get_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/GetBlurb', + request_serializer=messaging.GetBlurbRequest.serialize, + response_deserializer=messaging.Blurb.deserialize, + ) + return self._stubs['get_blurb'] + + @property + def update_blurb(self) -> Callable[ + [messaging.UpdateBlurbRequest], + messaging.Blurb]: + r"""Return a callable for the update blurb method over gRPC. + + Updates a blurb. + + Returns: + Callable[[~.UpdateBlurbRequest], + ~.Blurb]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_blurb' not in self._stubs: + self._stubs['update_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/UpdateBlurb', + request_serializer=messaging.UpdateBlurbRequest.serialize, + response_deserializer=messaging.Blurb.deserialize, + ) + return self._stubs['update_blurb'] + + @property + def delete_blurb(self) -> Callable[ + [messaging.DeleteBlurbRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete blurb method over gRPC. + + Deletes a blurb. + + Returns: + Callable[[~.DeleteBlurbRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_blurb' not in self._stubs: + self._stubs['delete_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/DeleteBlurb', + request_serializer=messaging.DeleteBlurbRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_blurb'] + + @property + def list_blurbs(self) -> Callable[ + [messaging.ListBlurbsRequest], + messaging.ListBlurbsResponse]: + r"""Return a callable for the list blurbs method over gRPC. + + Lists blurbs for a specific chat room or user profile + depending on the parent resource name. + + Returns: + Callable[[~.ListBlurbsRequest], + ~.ListBlurbsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_blurbs' not in self._stubs: + self._stubs['list_blurbs'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/ListBlurbs', + request_serializer=messaging.ListBlurbsRequest.serialize, + response_deserializer=messaging.ListBlurbsResponse.deserialize, + ) + return self._stubs['list_blurbs'] + + @property + def search_blurbs(self) -> Callable[ + [messaging.SearchBlurbsRequest], + operations_pb2.Operation]: + r"""Return a callable for the search blurbs method over gRPC. + + This method searches through all blurbs across all + rooms and profiles for blurbs containing to words found + in the query. Only posts that contain an exact match of + a queried word will be returned. + + Returns: + Callable[[~.SearchBlurbsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_blurbs' not in self._stubs: + self._stubs['search_blurbs'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/SearchBlurbs', + request_serializer=messaging.SearchBlurbsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['search_blurbs'] + + @property + def stream_blurbs(self) -> Callable[ + [messaging.StreamBlurbsRequest], + messaging.StreamBlurbsResponse]: + r"""Return a callable for the stream blurbs method over gRPC. + + This returns a stream that emits the blurbs that are + created for a particular chat room or user profile. + + Returns: + Callable[[~.StreamBlurbsRequest], + ~.StreamBlurbsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stream_blurbs' not in self._stubs: + self._stubs['stream_blurbs'] = self._logged_channel.unary_stream( + '/google.showcase.v1beta1.Messaging/StreamBlurbs', + request_serializer=messaging.StreamBlurbsRequest.serialize, + response_deserializer=messaging.StreamBlurbsResponse.deserialize, + ) + return self._stubs['stream_blurbs'] + + @property + def send_blurbs(self) -> Callable[ + [messaging.CreateBlurbRequest], + messaging.SendBlurbsResponse]: + r"""Return a callable for the send blurbs method over gRPC. + + This is a stream to create multiple blurbs. If an + invalid blurb is requested to be created, the stream + will close with an error. + + Returns: + Callable[[~.CreateBlurbRequest], + ~.SendBlurbsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'send_blurbs' not in self._stubs: + self._stubs['send_blurbs'] = self._logged_channel.stream_unary( + '/google.showcase.v1beta1.Messaging/SendBlurbs', + request_serializer=messaging.CreateBlurbRequest.serialize, + response_deserializer=messaging.SendBlurbsResponse.deserialize, + ) + return self._stubs['send_blurbs'] + + @property + def connect(self) -> Callable[ + [messaging.ConnectRequest], + messaging.StreamBlurbsResponse]: + r"""Return a callable for the connect method over gRPC. + + This method starts a bidirectional stream that + receives all blurbs that are being created after the + stream has started and sends requests to create blurbs. + If an invalid blurb is requested to be created, the + stream will close with an error. + + Returns: + Callable[[~.ConnectRequest], + ~.StreamBlurbsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'connect' not in self._stubs: + self._stubs['connect'] = self._logged_channel.stream_stream( + '/google.showcase.v1beta1.Messaging/Connect', + request_serializer=messaging.ConnectRequest.serialize, + response_deserializer=messaging.StreamBlurbsResponse.deserialize, + ) + return self._stubs['connect'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'MessagingGrpcTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0011029fc37e --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py @@ -0,0 +1,1108 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.showcase_v1beta1.types import messaging +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import MessagingTransport, DEFAULT_CLIENT_INFO +from .grpc import MessagingGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MessagingGrpcAsyncIOTransport(MessagingTransport): + """gRPC AsyncIO backend transport for Messaging. + + A simple messaging service that implements chat rooms and + profile posts. + This messaging service showcases the features that API clients + generated by gapic-generators implement. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'localhost:7469', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'localhost:7469', + 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: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_room(self) -> Callable[ + [messaging.CreateRoomRequest], + Awaitable[messaging.Room]]: + r"""Return a callable for the create room method over gRPC. + + Creates a room. + + Returns: + Callable[[~.CreateRoomRequest], + Awaitable[~.Room]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_room' not in self._stubs: + self._stubs['create_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/CreateRoom', + request_serializer=messaging.CreateRoomRequest.serialize, + response_deserializer=messaging.Room.deserialize, + ) + return self._stubs['create_room'] + + @property + def get_room(self) -> Callable[ + [messaging.GetRoomRequest], + Awaitable[messaging.Room]]: + r"""Return a callable for the get room method over gRPC. + + Retrieves the Room with the given resource name. + + Returns: + Callable[[~.GetRoomRequest], + Awaitable[~.Room]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_room' not in self._stubs: + self._stubs['get_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/GetRoom', + request_serializer=messaging.GetRoomRequest.serialize, + response_deserializer=messaging.Room.deserialize, + ) + return self._stubs['get_room'] + + @property + def update_room(self) -> Callable[ + [messaging.UpdateRoomRequest], + Awaitable[messaging.Room]]: + r"""Return a callable for the update room method over gRPC. + + Updates a room. + + Returns: + Callable[[~.UpdateRoomRequest], + Awaitable[~.Room]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_room' not in self._stubs: + self._stubs['update_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/UpdateRoom', + request_serializer=messaging.UpdateRoomRequest.serialize, + response_deserializer=messaging.Room.deserialize, + ) + return self._stubs['update_room'] + + @property + def delete_room(self) -> Callable[ + [messaging.DeleteRoomRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete room method over gRPC. + + Deletes a room and all of its blurbs. + + Returns: + Callable[[~.DeleteRoomRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_room' not in self._stubs: + self._stubs['delete_room'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/DeleteRoom', + request_serializer=messaging.DeleteRoomRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_room'] + + @property + def list_rooms(self) -> Callable[ + [messaging.ListRoomsRequest], + Awaitable[messaging.ListRoomsResponse]]: + r"""Return a callable for the list rooms method over gRPC. + + Lists all chat rooms. + + Returns: + Callable[[~.ListRoomsRequest], + Awaitable[~.ListRoomsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_rooms' not in self._stubs: + self._stubs['list_rooms'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/ListRooms', + request_serializer=messaging.ListRoomsRequest.serialize, + response_deserializer=messaging.ListRoomsResponse.deserialize, + ) + return self._stubs['list_rooms'] + + @property + def create_blurb(self) -> Callable[ + [messaging.CreateBlurbRequest], + Awaitable[messaging.Blurb]]: + r"""Return a callable for the create blurb method over gRPC. + + Creates a blurb. If the parent is a room, the blurb + is understood to be a message in that room. If the + parent is a profile, the blurb is understood to be a + post on the profile. + + Returns: + Callable[[~.CreateBlurbRequest], + Awaitable[~.Blurb]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_blurb' not in self._stubs: + self._stubs['create_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/CreateBlurb', + request_serializer=messaging.CreateBlurbRequest.serialize, + response_deserializer=messaging.Blurb.deserialize, + ) + return self._stubs['create_blurb'] + + @property + def get_blurb(self) -> Callable[ + [messaging.GetBlurbRequest], + Awaitable[messaging.Blurb]]: + r"""Return a callable for the get blurb method over gRPC. + + Retrieves the Blurb with the given resource name. + + Returns: + Callable[[~.GetBlurbRequest], + Awaitable[~.Blurb]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_blurb' not in self._stubs: + self._stubs['get_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/GetBlurb', + request_serializer=messaging.GetBlurbRequest.serialize, + response_deserializer=messaging.Blurb.deserialize, + ) + return self._stubs['get_blurb'] + + @property + def update_blurb(self) -> Callable[ + [messaging.UpdateBlurbRequest], + Awaitable[messaging.Blurb]]: + r"""Return a callable for the update blurb method over gRPC. + + Updates a blurb. + + Returns: + Callable[[~.UpdateBlurbRequest], + Awaitable[~.Blurb]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_blurb' not in self._stubs: + self._stubs['update_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/UpdateBlurb', + request_serializer=messaging.UpdateBlurbRequest.serialize, + response_deserializer=messaging.Blurb.deserialize, + ) + return self._stubs['update_blurb'] + + @property + def delete_blurb(self) -> Callable[ + [messaging.DeleteBlurbRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete blurb method over gRPC. + + Deletes a blurb. + + Returns: + Callable[[~.DeleteBlurbRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_blurb' not in self._stubs: + self._stubs['delete_blurb'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/DeleteBlurb', + request_serializer=messaging.DeleteBlurbRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_blurb'] + + @property + def list_blurbs(self) -> Callable[ + [messaging.ListBlurbsRequest], + Awaitable[messaging.ListBlurbsResponse]]: + r"""Return a callable for the list blurbs method over gRPC. + + Lists blurbs for a specific chat room or user profile + depending on the parent resource name. + + Returns: + Callable[[~.ListBlurbsRequest], + Awaitable[~.ListBlurbsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_blurbs' not in self._stubs: + self._stubs['list_blurbs'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/ListBlurbs', + request_serializer=messaging.ListBlurbsRequest.serialize, + response_deserializer=messaging.ListBlurbsResponse.deserialize, + ) + return self._stubs['list_blurbs'] + + @property + def search_blurbs(self) -> Callable[ + [messaging.SearchBlurbsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the search blurbs method over gRPC. + + This method searches through all blurbs across all + rooms and profiles for blurbs containing to words found + in the query. Only posts that contain an exact match of + a queried word will be returned. + + Returns: + Callable[[~.SearchBlurbsRequest], + 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 'search_blurbs' not in self._stubs: + self._stubs['search_blurbs'] = self._logged_channel.unary_unary( + '/google.showcase.v1beta1.Messaging/SearchBlurbs', + request_serializer=messaging.SearchBlurbsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['search_blurbs'] + + @property + def stream_blurbs(self) -> Callable[ + [messaging.StreamBlurbsRequest], + Awaitable[messaging.StreamBlurbsResponse]]: + r"""Return a callable for the stream blurbs method over gRPC. + + This returns a stream that emits the blurbs that are + created for a particular chat room or user profile. + + Returns: + Callable[[~.StreamBlurbsRequest], + Awaitable[~.StreamBlurbsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stream_blurbs' not in self._stubs: + self._stubs['stream_blurbs'] = self._logged_channel.unary_stream( + '/google.showcase.v1beta1.Messaging/StreamBlurbs', + request_serializer=messaging.StreamBlurbsRequest.serialize, + response_deserializer=messaging.StreamBlurbsResponse.deserialize, + ) + return self._stubs['stream_blurbs'] + + @property + def send_blurbs(self) -> Callable[ + [messaging.CreateBlurbRequest], + Awaitable[messaging.SendBlurbsResponse]]: + r"""Return a callable for the send blurbs method over gRPC. + + This is a stream to create multiple blurbs. If an + invalid blurb is requested to be created, the stream + will close with an error. + + Returns: + Callable[[~.CreateBlurbRequest], + Awaitable[~.SendBlurbsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'send_blurbs' not in self._stubs: + self._stubs['send_blurbs'] = self._logged_channel.stream_unary( + '/google.showcase.v1beta1.Messaging/SendBlurbs', + request_serializer=messaging.CreateBlurbRequest.serialize, + response_deserializer=messaging.SendBlurbsResponse.deserialize, + ) + return self._stubs['send_blurbs'] + + @property + def connect(self) -> Callable[ + [messaging.ConnectRequest], + Awaitable[messaging.StreamBlurbsResponse]]: + r"""Return a callable for the connect method over gRPC. + + This method starts a bidirectional stream that + receives all blurbs that are being created after the + stream has started and sends requests to create blurbs. + If an invalid blurb is requested to be created, the + stream will close with an error. + + Returns: + Callable[[~.ConnectRequest], + Awaitable[~.StreamBlurbsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'connect' not in self._stubs: + self._stubs['connect'] = self._logged_channel.stream_stream( + '/google.showcase.v1beta1.Messaging/Connect', + request_serializer=messaging.ConnectRequest.serialize, + response_deserializer=messaging.StreamBlurbsResponse.deserialize, + ) + return self._stubs['connect'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_room: self._wrap_method( + self.create_room, + default_timeout=None, + client_info=client_info, + ), + self.get_room: self._wrap_method( + self.get_room, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.update_room: self._wrap_method( + self.update_room, + default_timeout=None, + client_info=client_info, + ), + self.delete_room: self._wrap_method( + self.delete_room, + default_timeout=None, + client_info=client_info, + ), + self.list_rooms: self._wrap_method( + self.list_rooms, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.create_blurb: self._wrap_method( + self.create_blurb, + default_timeout=None, + client_info=client_info, + ), + self.get_blurb: self._wrap_method( + self.get_blurb, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.update_blurb: self._wrap_method( + self.update_blurb, + default_timeout=None, + client_info=client_info, + ), + self.delete_blurb: self._wrap_method( + self.delete_blurb, + default_timeout=None, + client_info=client_info, + ), + self.list_blurbs: self._wrap_method( + self.list_blurbs, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.search_blurbs: self._wrap_method( + self.search_blurbs, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.stream_blurbs: self._wrap_method( + self.stream_blurbs, + default_timeout=None, + client_info=client_info, + ), + self.send_blurbs: self._wrap_method( + self.send_blurbs, + default_timeout=None, + client_info=client_info, + ), + self.connect: self._wrap_method( + self.connect, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=3.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=10.0, + ), + default_timeout=10.0, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + 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.get_iam_policy: self._wrap_method( + self.get_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.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_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.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'MessagingGrpcAsyncIOTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py new file mode 100644 index 000000000000..47c17322d876 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py @@ -0,0 +1,3559 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # 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.showcase_v1beta1 import _compat as rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +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.showcase_v1beta1.types import messaging +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseMessagingRestTransport +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 + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class MessagingRestInterceptor: + """Interceptor for Messaging. + + 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 MessagingRestTransport. + + .. code-block:: python + class MyCustomMessagingInterceptor(MessagingRestInterceptor): + def pre_create_blurb(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_blurb(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_room(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_room(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_blurb(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_room(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_blurb(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_blurb(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_room(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_room(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_blurbs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_blurbs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_rooms(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_rooms(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_blurbs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_blurbs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stream_blurbs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stream_blurbs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_blurb(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_blurb(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_room(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_room(self, response): + logging.log(f"Received response: {response}") + return response + + transport = MessagingRestTransport(interceptor=MyCustomMessagingInterceptor()) + client = MessagingClient(transport=transport) + + + """ + def pre_create_blurb(self, request: messaging.CreateBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.CreateBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_blurb + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_create_blurb(self, response: messaging.Blurb) -> messaging.Blurb: + """Post-rpc interceptor for create_blurb + + DEPRECATED. Please use the `post_create_blurb_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_create_blurb` interceptor runs + before the `post_create_blurb_with_metadata` interceptor. + """ + return response + + def post_create_blurb_with_metadata(self, response: messaging.Blurb, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Blurb, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_blurb + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_create_blurb_with_metadata` + interceptor in new development instead of the `post_create_blurb` interceptor. + When both interceptors are used, this `post_create_blurb_with_metadata` interceptor runs after the + `post_create_blurb` interceptor. The (possibly modified) response returned by + `post_create_blurb` will be passed to + `post_create_blurb_with_metadata`. + """ + return response, metadata + + def pre_create_room(self, request: messaging.CreateRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.CreateRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_room + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_create_room(self, response: messaging.Room) -> messaging.Room: + """Post-rpc interceptor for create_room + + DEPRECATED. Please use the `post_create_room_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_create_room` interceptor runs + before the `post_create_room_with_metadata` interceptor. + """ + return response + + def post_create_room_with_metadata(self, response: messaging.Room, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Room, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_room + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_create_room_with_metadata` + interceptor in new development instead of the `post_create_room` interceptor. + When both interceptors are used, this `post_create_room_with_metadata` interceptor runs after the + `post_create_room` interceptor. The (possibly modified) response returned by + `post_create_room` will be passed to + `post_create_room_with_metadata`. + """ + return response, metadata + + def pre_delete_blurb(self, request: messaging.DeleteBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.DeleteBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_blurb + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def pre_delete_room(self, request: messaging.DeleteRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.DeleteRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_room + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def pre_get_blurb(self, request: messaging.GetBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.GetBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_blurb + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_get_blurb(self, response: messaging.Blurb) -> messaging.Blurb: + """Post-rpc interceptor for get_blurb + + DEPRECATED. Please use the `post_get_blurb_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_get_blurb` interceptor runs + before the `post_get_blurb_with_metadata` interceptor. + """ + return response + + def post_get_blurb_with_metadata(self, response: messaging.Blurb, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Blurb, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_blurb + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_get_blurb_with_metadata` + interceptor in new development instead of the `post_get_blurb` interceptor. + When both interceptors are used, this `post_get_blurb_with_metadata` interceptor runs after the + `post_get_blurb` interceptor. The (possibly modified) response returned by + `post_get_blurb` will be passed to + `post_get_blurb_with_metadata`. + """ + return response, metadata + + def pre_get_room(self, request: messaging.GetRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.GetRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_room + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_get_room(self, response: messaging.Room) -> messaging.Room: + """Post-rpc interceptor for get_room + + DEPRECATED. Please use the `post_get_room_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_get_room` interceptor runs + before the `post_get_room_with_metadata` interceptor. + """ + return response + + def post_get_room_with_metadata(self, response: messaging.Room, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Room, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_room + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_get_room_with_metadata` + interceptor in new development instead of the `post_get_room` interceptor. + When both interceptors are used, this `post_get_room_with_metadata` interceptor runs after the + `post_get_room` interceptor. The (possibly modified) response returned by + `post_get_room` will be passed to + `post_get_room_with_metadata`. + """ + return response, metadata + + def pre_list_blurbs(self, request: messaging.ListBlurbsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListBlurbsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_blurbs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_list_blurbs(self, response: messaging.ListBlurbsResponse) -> messaging.ListBlurbsResponse: + """Post-rpc interceptor for list_blurbs + + DEPRECATED. Please use the `post_list_blurbs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_list_blurbs` interceptor runs + before the `post_list_blurbs_with_metadata` interceptor. + """ + return response + + def post_list_blurbs_with_metadata(self, response: messaging.ListBlurbsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListBlurbsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_blurbs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_list_blurbs_with_metadata` + interceptor in new development instead of the `post_list_blurbs` interceptor. + When both interceptors are used, this `post_list_blurbs_with_metadata` interceptor runs after the + `post_list_blurbs` interceptor. The (possibly modified) response returned by + `post_list_blurbs` will be passed to + `post_list_blurbs_with_metadata`. + """ + return response, metadata + + def pre_list_rooms(self, request: messaging.ListRoomsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListRoomsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_rooms + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_list_rooms(self, response: messaging.ListRoomsResponse) -> messaging.ListRoomsResponse: + """Post-rpc interceptor for list_rooms + + DEPRECATED. Please use the `post_list_rooms_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_list_rooms` interceptor runs + before the `post_list_rooms_with_metadata` interceptor. + """ + return response + + def post_list_rooms_with_metadata(self, response: messaging.ListRoomsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListRoomsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_rooms + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_list_rooms_with_metadata` + interceptor in new development instead of the `post_list_rooms` interceptor. + When both interceptors are used, this `post_list_rooms_with_metadata` interceptor runs after the + `post_list_rooms` interceptor. The (possibly modified) response returned by + `post_list_rooms` will be passed to + `post_list_rooms_with_metadata`. + """ + return response, metadata + + def pre_search_blurbs(self, request: messaging.SearchBlurbsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.SearchBlurbsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for search_blurbs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_search_blurbs(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for search_blurbs + + DEPRECATED. Please use the `post_search_blurbs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_search_blurbs` interceptor runs + before the `post_search_blurbs_with_metadata` interceptor. + """ + return response + + def post_search_blurbs_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for search_blurbs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_search_blurbs_with_metadata` + interceptor in new development instead of the `post_search_blurbs` interceptor. + When both interceptors are used, this `post_search_blurbs_with_metadata` interceptor runs after the + `post_search_blurbs` interceptor. The (possibly modified) response returned by + `post_search_blurbs` will be passed to + `post_search_blurbs_with_metadata`. + """ + return response, metadata + + def pre_stream_blurbs(self, request: messaging.StreamBlurbsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.StreamBlurbsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for stream_blurbs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_stream_blurbs(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for stream_blurbs + + DEPRECATED. Please use the `post_stream_blurbs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_stream_blurbs` interceptor runs + before the `post_stream_blurbs_with_metadata` interceptor. + """ + return response + + def post_stream_blurbs_with_metadata(self, response: rest_streaming.ResponseIterator, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for stream_blurbs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_stream_blurbs_with_metadata` + interceptor in new development instead of the `post_stream_blurbs` interceptor. + When both interceptors are used, this `post_stream_blurbs_with_metadata` interceptor runs after the + `post_stream_blurbs` interceptor. The (possibly modified) response returned by + `post_stream_blurbs` will be passed to + `post_stream_blurbs_with_metadata`. + """ + return response, metadata + + def pre_update_blurb(self, request: messaging.UpdateBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.UpdateBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_blurb + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_update_blurb(self, response: messaging.Blurb) -> messaging.Blurb: + """Post-rpc interceptor for update_blurb + + DEPRECATED. Please use the `post_update_blurb_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_update_blurb` interceptor runs + before the `post_update_blurb_with_metadata` interceptor. + """ + return response + + def post_update_blurb_with_metadata(self, response: messaging.Blurb, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Blurb, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_blurb + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_update_blurb_with_metadata` + interceptor in new development instead of the `post_update_blurb` interceptor. + When both interceptors are used, this `post_update_blurb_with_metadata` interceptor runs after the + `post_update_blurb` interceptor. The (possibly modified) response returned by + `post_update_blurb` will be passed to + `post_update_blurb_with_metadata`. + """ + return response, metadata + + def pre_update_room(self, request: messaging.UpdateRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.UpdateRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_room + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging server. + """ + return request, metadata + + def post_update_room(self, response: messaging.Room) -> messaging.Room: + """Post-rpc interceptor for update_room + + DEPRECATED. Please use the `post_update_room_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Messaging server but before + it is returned to user code. This `post_update_room` interceptor runs + before the `post_update_room_with_metadata` interceptor. + """ + return response + + def post_update_room_with_metadata(self, response: messaging.Room, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Room, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_room + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Messaging server but before it is returned to user code. + + We recommend only using this `post_update_room_with_metadata` + interceptor in new development instead of the `post_update_room` interceptor. + When both interceptors are used, this `post_update_room_with_metadata` interceptor runs after the + `post_update_room` interceptor. The (possibly modified) response returned by + `post_update_room` will be passed to + `post_update_room_with_metadata`. + """ + return response, metadata + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Messaging 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 Messaging server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class MessagingRestStub: + _session: AuthorizedSession + _host: str + _interceptor: MessagingRestInterceptor + + +class MessagingRestTransport(_BaseMessagingRestTransport): + """REST backend synchronous transport for Messaging. + + A simple messaging service that implements chat rooms and + profile posts. + This messaging service showcases the features that API clients + generated by gapic-generators implement. + + This 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 = 'localhost:7469', + 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[MessagingRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'localhost:7469'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[MessagingRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 MessagingRestInterceptor() + 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.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/operations', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=operations/**}', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta1/{name=operations/**}', + }, + ], + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta1/{name=operations/**}:cancel', + }, + ], + } + + 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="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _Connect(_BaseMessagingRestTransport._BaseConnect, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.Connect") + + def __call__(self, + request: messaging.ConnectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method Connect is not available over REST transport" + ) + class _CreateBlurb(_BaseMessagingRestTransport._BaseCreateBlurb, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.CreateBlurb") + + @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: messaging.CreateBlurbRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.Blurb: + r"""Call the create blurb method over HTTP. + + Args: + request (~.messaging.CreateBlurbRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\CreateBlurb + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + + http_options = _BaseMessagingRestTransport._BaseCreateBlurb._get_http_options() + request, metadata = self._interceptor.pre_create_blurb(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseCreateBlurb, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.CreateBlurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "CreateBlurb", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._CreateBlurb._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 = messaging.Blurb() + pb_resp = messaging.Blurb.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_blurb(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_blurb_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.Blurb.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.create_blurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "CreateBlurb", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateRoom(_BaseMessagingRestTransport._BaseCreateRoom, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.CreateRoom") + + @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: messaging.CreateRoomRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.Room: + r"""Call the create room method over HTTP. + + Args: + request (~.messaging.CreateRoomRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\CreateRoom + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.Room: + A chat room. + """ + + http_options = _BaseMessagingRestTransport._BaseCreateRoom._get_http_options() + request, metadata = self._interceptor.pre_create_room(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseCreateRoom, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.CreateRoom", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "CreateRoom", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._CreateRoom._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 = messaging.Room() + pb_resp = messaging.Room.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_room(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_room_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.Room.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.create_room", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "CreateRoom", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBlurb(_BaseMessagingRestTransport._BaseDeleteBlurb, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.DeleteBlurb") + + @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: messaging.DeleteBlurbRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete blurb method over HTTP. + + Args: + request (~.messaging.DeleteBlurbRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\DeleteBlurb + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMessagingRestTransport._BaseDeleteBlurb._get_http_options() + request, metadata = self._interceptor.pre_delete_blurb(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseDeleteBlurb, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.DeleteBlurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "DeleteBlurb", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._DeleteBlurb._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteRoom(_BaseMessagingRestTransport._BaseDeleteRoom, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.DeleteRoom") + + @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: messaging.DeleteRoomRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete room method over HTTP. + + Args: + request (~.messaging.DeleteRoomRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\DeleteRoom + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMessagingRestTransport._BaseDeleteRoom._get_http_options() + request, metadata = self._interceptor.pre_delete_room(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseDeleteRoom, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.DeleteRoom", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "DeleteRoom", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._DeleteRoom._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetBlurb(_BaseMessagingRestTransport._BaseGetBlurb, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.GetBlurb") + + @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: messaging.GetBlurbRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.Blurb: + r"""Call the get blurb method over HTTP. + + Args: + request (~.messaging.GetBlurbRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\GetBlurb + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + + http_options = _BaseMessagingRestTransport._BaseGetBlurb._get_http_options() + request, metadata = self._interceptor.pre_get_blurb(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseGetBlurb, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.GetBlurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetBlurb", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._GetBlurb._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 = messaging.Blurb() + pb_resp = messaging.Blurb.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_blurb(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_blurb_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.Blurb.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.get_blurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetBlurb", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRoom(_BaseMessagingRestTransport._BaseGetRoom, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.GetRoom") + + @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: messaging.GetRoomRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.Room: + r"""Call the get room method over HTTP. + + Args: + request (~.messaging.GetRoomRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\GetRoom + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.Room: + A chat room. + """ + + http_options = _BaseMessagingRestTransport._BaseGetRoom._get_http_options() + request, metadata = self._interceptor.pre_get_room(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseGetRoom, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.GetRoom", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetRoom", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._GetRoom._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 = messaging.Room() + pb_resp = messaging.Room.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_room(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_room_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.Room.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.get_room", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetRoom", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBlurbs(_BaseMessagingRestTransport._BaseListBlurbs, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.ListBlurbs") + + @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: messaging.ListBlurbsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.ListBlurbsResponse: + r"""Call the list blurbs method over HTTP. + + Args: + request (~.messaging.ListBlurbsRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\ListBlurbs + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.ListBlurbsResponse: + The response message for the + google.showcase.v1beta1.Messaging\ListBlurbs + method. + + """ + + http_options = _BaseMessagingRestTransport._BaseListBlurbs._get_http_options() + request, metadata = self._interceptor.pre_list_blurbs(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseListBlurbs, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.ListBlurbs", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListBlurbs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._ListBlurbs._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 = messaging.ListBlurbsResponse() + pb_resp = messaging.ListBlurbsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_blurbs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_blurbs_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.ListBlurbsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.list_blurbs", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListBlurbs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRooms(_BaseMessagingRestTransport._BaseListRooms, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.ListRooms") + + @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: messaging.ListRoomsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.ListRoomsResponse: + r"""Call the list rooms method over HTTP. + + Args: + request (~.messaging.ListRoomsRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\ListRooms + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.ListRoomsResponse: + The response message for the + google.showcase.v1beta1.Messaging\ListRooms + method. + + """ + + http_options = _BaseMessagingRestTransport._BaseListRooms._get_http_options() + request, metadata = self._interceptor.pre_list_rooms(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseListRooms, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.ListRooms", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListRooms", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._ListRooms._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 = messaging.ListRoomsResponse() + pb_resp = messaging.ListRoomsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_rooms(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_rooms_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.ListRoomsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.list_rooms", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListRooms", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchBlurbs(_BaseMessagingRestTransport._BaseSearchBlurbs, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.SearchBlurbs") + + @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: messaging.SearchBlurbsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the search blurbs method over HTTP. + + Args: + request (~.messaging.SearchBlurbsRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\SearchBlurbs + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseMessagingRestTransport._BaseSearchBlurbs._get_http_options() + request, metadata = self._interceptor.pre_search_blurbs(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseSearchBlurbs, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.SearchBlurbs", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "SearchBlurbs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._SearchBlurbs._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_search_blurbs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_search_blurbs_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.search_blurbs", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "SearchBlurbs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SendBlurbs(_BaseMessagingRestTransport._BaseSendBlurbs, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.SendBlurbs") + + def __call__(self, + request: messaging.CreateBlurbRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.SendBlurbsResponse: + raise NotImplementedError( + "Method SendBlurbs is not available over REST transport" + ) + class _StreamBlurbs(_BaseMessagingRestTransport._BaseStreamBlurbs, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.StreamBlurbs") + + @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, + stream=True, + ) + return response + + def __call__(self, + request: messaging.StreamBlurbsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the stream blurbs method over HTTP. + + Args: + request (~.messaging.StreamBlurbsRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.StreamBlurbsResponse: + The response message for the + google.showcase.v1beta1.Messaging\StreamBlurbs + method. + + """ + + http_options = _BaseMessagingRestTransport._BaseStreamBlurbs._get_http_options() + request, metadata = self._interceptor.pre_stream_blurbs(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseStreamBlurbs, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.StreamBlurbs", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "StreamBlurbs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._StreamBlurbs._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 = rest_streaming.ResponseIterator(response, messaging.StreamBlurbsResponse) + + resp = self._interceptor.post_stream_blurbs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_stream_blurbs_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + http_response = { + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.stream_blurbs", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "StreamBlurbs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBlurb(_BaseMessagingRestTransport._BaseUpdateBlurb, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.UpdateBlurb") + + @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: messaging.UpdateBlurbRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.Blurb: + r"""Call the update blurb method over HTTP. + + Args: + request (~.messaging.UpdateBlurbRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\UpdateBlurb + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.Blurb: + This protocol buffer message + represents a blurb sent to a chat room + or posted on a user profile. + + """ + + http_options = _BaseMessagingRestTransport._BaseUpdateBlurb._get_http_options() + request, metadata = self._interceptor.pre_update_blurb(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseUpdateBlurb, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.UpdateBlurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "UpdateBlurb", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._UpdateBlurb._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 = messaging.Blurb() + pb_resp = messaging.Blurb.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_blurb(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_blurb_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.Blurb.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.update_blurb", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "UpdateBlurb", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateRoom(_BaseMessagingRestTransport._BaseUpdateRoom, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.UpdateRoom") + + @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: messaging.UpdateRoomRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> messaging.Room: + r"""Call the update room method over HTTP. + + Args: + request (~.messaging.UpdateRoomRequest): + The request object. The request message for the + google.showcase.v1beta1.Messaging\UpdateRoom + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.messaging.Room: + A chat room. + """ + + http_options = _BaseMessagingRestTransport._BaseUpdateRoom._get_http_options() + request, metadata = self._interceptor.pre_update_room(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseUpdateRoom, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.UpdateRoom", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "UpdateRoom", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._UpdateRoom._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 = messaging.Room() + pb_resp = messaging.Room.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_room(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_room_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = messaging.Room.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingClient.update_room", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "UpdateRoom", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def connect(self) -> Callable[ + [messaging.ConnectRequest], + messaging.StreamBlurbsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Connect(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_blurb(self) -> Callable[ + [messaging.CreateBlurbRequest], + messaging.Blurb]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBlurb(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_room(self) -> Callable[ + [messaging.CreateRoomRequest], + messaging.Room]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateRoom(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_blurb(self) -> Callable[ + [messaging.DeleteBlurbRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBlurb(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_room(self) -> Callable[ + [messaging.DeleteRoomRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteRoom(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_blurb(self) -> Callable[ + [messaging.GetBlurbRequest], + messaging.Blurb]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBlurb(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_room(self) -> Callable[ + [messaging.GetRoomRequest], + messaging.Room]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetRoom(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_blurbs(self) -> Callable[ + [messaging.ListBlurbsRequest], + messaging.ListBlurbsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBlurbs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_rooms(self) -> Callable[ + [messaging.ListRoomsRequest], + messaging.ListRoomsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListRooms(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_blurbs(self) -> Callable[ + [messaging.SearchBlurbsRequest], + 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._SearchBlurbs(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_blurbs(self) -> Callable[ + [messaging.CreateBlurbRequest], + messaging.SendBlurbsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendBlurbs(self._session, self._host, self._interceptor) # type: ignore + + @property + def stream_blurbs(self) -> Callable[ + [messaging.StreamBlurbsRequest], + messaging.StreamBlurbsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StreamBlurbs(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_blurb(self) -> Callable[ + [messaging.UpdateBlurbRequest], + messaging.Blurb]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBlurb(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_room(self) -> Callable[ + [messaging.UpdateRoomRequest], + messaging.Room]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateRoom(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseMessagingRestTransport._BaseListLocations, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseMessagingRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseListLocations, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.ListLocations", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.ListLocations", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseMessagingRestTransport._BaseGetLocation, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseMessagingRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseGetLocation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.GetLocation", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.GetLocation", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseMessagingRestTransport._BaseSetIamPolicy, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseMessagingRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseSetIamPolicy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.SetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseMessagingRestTransport._BaseGetIamPolicy, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseMessagingRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseGetIamPolicy, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.GetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseMessagingRestTransport._BaseTestIamPermissions, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseMessagingRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseTestIamPermissions, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.TestIamPermissions", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseMessagingRestTransport._BaseListOperations, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseMessagingRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseListOperations, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.ListOperations", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.ListOperations", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseMessagingRestTransport._BaseGetOperation, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseMessagingRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseGetOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.GetOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.showcase_v1beta1.MessagingAsyncClient.GetOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseMessagingRestTransport._BaseDeleteOperation, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMessagingRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseDeleteOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.DeleteOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._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 cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseMessagingRestTransport._BaseCancelOperation, MessagingRestStub): + def __hash__(self): + return hash("MessagingRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMessagingRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request, body, query_params = rest_helpers.transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMessagingRestTransport._BaseCancelOperation, + "__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.showcase_v1beta1.MessagingClient.CancelOperation", + extra = { + "serviceName": "google.showcase.v1beta1.Messaging", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MessagingRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'MessagingRestTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py new file mode 100644 index 000000000000..13e97282bc2f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py @@ -0,0 +1,524 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 MessagingTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.showcase_v1beta1.types import messaging +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseMessagingRestTransport(MessagingTransport): + """Base REST backend transport for Messaging. + + 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 = 'localhost:7469', + 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: 'localhost:7469'). + 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 _BaseConnect: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseCreateBlurb: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=rooms/*}/blurbs', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{parent=users/*/profile}/blurbs', + 'body': '*', + }, + ] + return http_options + + class _BaseCreateRoom: + 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': '/v1beta1/rooms', + 'body': '*', + }, + ] + return http_options + + class _BaseDeleteBlurb: + 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': '/v1beta1/{name=rooms/*/blurbs/*}', + }, + { + 'method': 'delete', + 'uri': '/v1beta1/{name=users/*/profile/blurbs/*}', + }, + ] + return http_options + + class _BaseDeleteRoom: + 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': '/v1beta1/{name=rooms/*}', + }, + ] + return http_options + + class _BaseGetBlurb: + 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': '/v1beta1/{name=rooms/*/blurbs/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{name=users/*/profile/blurbs/*}', + }, + ] + return http_options + + class _BaseGetRoom: + 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': '/v1beta1/{name=rooms/*}', + }, + ] + return http_options + + class _BaseListBlurbs: + 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': '/v1beta1/{parent=rooms/*}/blurbs', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{parent=users/*/profile}/blurbs', + }, + ] + return http_options + + class _BaseListRooms: + 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': '/v1beta1/rooms', + }, + ] + return http_options + + class _BaseSearchBlurbs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=rooms/*}/blurbs:search', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{parent=users/*/profile}/blurbs:search', + }, + ] + return http_options + + class _BaseSendBlurbs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseStreamBlurbs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{name=rooms/*}/blurbs:stream', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{name=users/*/profile}/blurbs:stream', + 'body': '*', + }, + ] + return http_options + + class _BaseUpdateBlurb: + 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': '/v1beta1/{blurb.name=rooms/*/blurbs/*}', + 'body': 'blurb', + }, + { + 'method': 'patch', + 'uri': '/v1beta1/{blurb.name=users/*/profile/blurbs/*}', + 'body': 'blurb', + }, + ] + return http_options + + class _BaseUpdateRoom: + 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': '/v1beta1/{room.name=rooms/*}', + 'body': 'room', + }, + ] + return http_options + + 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': '/v1beta1/{name=projects/*}/locations', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=projects/*/locations/*}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=sequences/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=rooms/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{resource=sequences/*}:getIamPolicy', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{resource=users/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1beta1/{resource=sequences/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + pass + + 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': '/v1beta1/operations', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}', + }, + ] + return http_options + + pass + + 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': '/v1beta1/{name=operations/**}:cancel', + }, + ] + return http_options + + pass + + +__all__=( + '_BaseMessagingRestTransport', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py new file mode 100644 index 000000000000..1b940c7a2478 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .echo import ( + BlockRequest, + BlockResponse, + EchoErrorDetailsRequest, + EchoErrorDetailsResponse, + EchoRequest, + EchoResponse, + ErrorWithMultipleDetails, + ErrorWithSingleDetail, + ExpandRequest, + PagedExpandLegacyMappedResponse, + PagedExpandLegacyRequest, + PagedExpandRequest, + PagedExpandResponse, + PagedExpandResponseList, + WaitMetadata, + WaitRequest, + WaitResponse, + Severity, +) +from .identity import ( + CreateUserRequest, + DeleteUserRequest, + GetUserRequest, + ListUsersRequest, + ListUsersResponse, + UpdateUserRequest, + User, +) +from .messaging import ( + Blurb, + ConnectRequest, + CreateBlurbRequest, + CreateRoomRequest, + DeleteBlurbRequest, + DeleteRoomRequest, + GetBlurbRequest, + GetRoomRequest, + ListBlurbsRequest, + ListBlurbsResponse, + ListRoomsRequest, + ListRoomsResponse, + Room, + SearchBlurbsMetadata, + SearchBlurbsRequest, + SearchBlurbsResponse, + SendBlurbsResponse, + StreamBlurbsRequest, + StreamBlurbsResponse, + UpdateBlurbRequest, + UpdateRoomRequest, +) + +__all__ = ( + 'BlockRequest', + 'BlockResponse', + 'EchoErrorDetailsRequest', + 'EchoErrorDetailsResponse', + 'EchoRequest', + 'EchoResponse', + 'ErrorWithMultipleDetails', + 'ErrorWithSingleDetail', + 'ExpandRequest', + 'PagedExpandLegacyMappedResponse', + 'PagedExpandLegacyRequest', + 'PagedExpandRequest', + 'PagedExpandResponse', + 'PagedExpandResponseList', + 'WaitMetadata', + 'WaitRequest', + 'WaitResponse', + 'Severity', + 'CreateUserRequest', + 'DeleteUserRequest', + 'GetUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + 'UpdateUserRequest', + 'User', + 'Blurb', + 'ConnectRequest', + 'CreateBlurbRequest', + 'CreateRoomRequest', + 'DeleteBlurbRequest', + 'DeleteRoomRequest', + 'GetBlurbRequest', + 'GetRoomRequest', + 'ListBlurbsRequest', + 'ListBlurbsResponse', + 'ListRoomsRequest', + 'ListRoomsResponse', + 'Room', + 'SearchBlurbsMetadata', + 'SearchBlurbsRequest', + 'SearchBlurbsResponse', + 'SendBlurbsResponse', + 'StreamBlurbsRequest', + 'StreamBlurbsResponse', + 'UpdateBlurbRequest', + 'UpdateRoomRequest', +) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py new file mode 100644 index 000000000000..6522ce6eec90 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.protobuf.any_pb2 as any_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.showcase.v1beta1', + manifest={ + 'Severity', + 'EchoRequest', + 'EchoResponse', + 'EchoErrorDetailsRequest', + 'EchoErrorDetailsResponse', + 'ErrorWithSingleDetail', + 'ErrorWithMultipleDetails', + 'ExpandRequest', + 'PagedExpandRequest', + 'PagedExpandLegacyRequest', + 'PagedExpandResponse', + 'PagedExpandResponseList', + 'PagedExpandLegacyMappedResponse', + 'WaitRequest', + 'WaitResponse', + 'WaitMetadata', + 'BlockRequest', + 'BlockResponse', + }, +) + + +class Severity(proto.Enum): + r"""A severity enum used to test enum capabilities in GAPIC + surfaces. + + Values: + UNNECESSARY (0): + No description available. + NECESSARY (1): + No description available. + URGENT (2): + No description available. + CRITICAL (3): + No description available. + """ + UNNECESSARY = 0 + NECESSARY = 1 + URGENT = 2 + CRITICAL = 3 + + +class EchoRequest(proto.Message): + r"""The request message used for the Echo, Collect and Chat + methods. If content or opt are set in this message then the + request will succeed. If status is set in this message then the + status will be returned as an error. + + 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: + content (str): + The content to be echoed by the server. + + This field is a member of `oneof`_ ``response``. + error (google.rpc.status_pb2.Status): + The error to be thrown by the server. + + This field is a member of `oneof`_ ``response``. + severity (google.showcase_v1beta1.types.Severity): + The severity to be echoed by the server. + header (str): + Optional. This field can be set to test the + routing annotation on the Echo method. + other_header (str): + Optional. This field can be set to test the + routing annotation on the Echo method. + request_id (str): + To facilitate testing of + https://google.aip.dev/client-libraries/4235 + other_request_id (str): + To facilitate testing of + https://google.aip.dev/client-libraries/4235 + + This field is a member of `oneof`_ ``_other_request_id``. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + oneof='response', + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message=status_pb2.Status, + ) + severity: 'Severity' = proto.Field( + proto.ENUM, + number=3, + enum='Severity', + ) + header: str = proto.Field( + proto.STRING, + number=4, + ) + other_header: str = proto.Field( + proto.STRING, + number=5, + ) + request_id: str = proto.Field( + proto.STRING, + number=7, + ) + other_request_id: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + + +class EchoResponse(proto.Message): + r"""The response message for the Echo methods. + + Attributes: + content (str): + The content specified in the request. + severity (google.showcase_v1beta1.types.Severity): + The severity specified in the request. + request_id (str): + The request ID specified or autopopulated in + the request. + other_request_id (str): + The other request ID specified or + autopopulated in the request. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + severity: 'Severity' = proto.Field( + proto.ENUM, + number=2, + enum='Severity', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + other_request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class EchoErrorDetailsRequest(proto.Message): + r"""The request message used for the EchoErrorDetails method. + + Attributes: + single_detail_text (str): + Content to return in a singular ``*.error.details`` field of + type ``google.protobuf.Any`` + multi_detail_text (MutableSequence[str]): + Content to return in a repeated ``*.error.details`` field of + type ``google.protobuf.Any`` + """ + + single_detail_text: str = proto.Field( + proto.STRING, + number=1, + ) + multi_detail_text: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class EchoErrorDetailsResponse(proto.Message): + r"""The response message used for the EchoErrorDetails method. + + Attributes: + single_detail (google.showcase_v1beta1.types.EchoErrorDetailsResponse.SingleDetail): + + multiple_details (google.showcase_v1beta1.types.EchoErrorDetailsResponse.MultipleDetails): + + """ + + class SingleDetail(proto.Message): + r""" + + Attributes: + error (google.showcase_v1beta1.types.ErrorWithSingleDetail): + + """ + + error: 'ErrorWithSingleDetail' = proto.Field( + proto.MESSAGE, + number=1, + message='ErrorWithSingleDetail', + ) + + class MultipleDetails(proto.Message): + r""" + + Attributes: + error (google.showcase_v1beta1.types.ErrorWithMultipleDetails): + + """ + + error: 'ErrorWithMultipleDetails' = proto.Field( + proto.MESSAGE, + number=1, + message='ErrorWithMultipleDetails', + ) + + single_detail: SingleDetail = proto.Field( + proto.MESSAGE, + number=1, + message=SingleDetail, + ) + multiple_details: MultipleDetails = proto.Field( + proto.MESSAGE, + number=2, + message=MultipleDetails, + ) + + +class ErrorWithSingleDetail(proto.Message): + r""" + + Attributes: + details (google.protobuf.any_pb2.Any): + + """ + + details: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=1, + message=any_pb2.Any, + ) + + +class ErrorWithMultipleDetails(proto.Message): + r""" + + Attributes: + details (MutableSequence[google.protobuf.any_pb2.Any]): + + """ + + details: MutableSequence[any_pb2.Any] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=any_pb2.Any, + ) + + +class ExpandRequest(proto.Message): + r"""The request message for the Expand method. + + Attributes: + content (str): + The content that will be split into words and + returned on the stream. + error (google.rpc.status_pb2.Status): + The error that is thrown after all words are + sent on the stream. + stream_wait_time (google.protobuf.duration_pb2.Duration): + The wait time between each server streaming + messages + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + stream_wait_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + +class PagedExpandRequest(proto.Message): + r"""The request for the PagedExpand method. + + Attributes: + content (str): + The string to expand. + page_size (int): + The number of words to returned in each page. + page_token (str): + The position of the page to be returned. + """ + + content: 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 PagedExpandLegacyRequest(proto.Message): + r"""The request for the PagedExpandLegacy method. This is a + pattern used by some legacy APIs. New APIs should NOT use this + pattern, but rather something like PagedExpandRequest which + conforms to aip.dev/158. + + Attributes: + content (str): + The string to expand. + max_results (int): + The number of words to returned in each page. (-- + aip.dev/not-precedent: This is a legacy, non-standard + pattern that violates aip.dev/158. Ordinarily, this should + be page_size. --) + page_token (str): + The position of the page to be returned. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + max_results: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class PagedExpandResponse(proto.Message): + r"""The response for the PagedExpand method. + + Attributes: + responses (MutableSequence[google.showcase_v1beta1.types.EchoResponse]): + The words that were expanded. + next_page_token (str): + The next page token. + """ + + @property + def raw_page(self): + return self + + responses: MutableSequence['EchoResponse'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EchoResponse', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PagedExpandResponseList(proto.Message): + r"""A list of words. + + Attributes: + words (MutableSequence[str]): + + """ + + words: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class PagedExpandLegacyMappedResponse(proto.Message): + r""" + + Attributes: + alphabetized (MutableMapping[str, google.showcase_v1beta1.types.PagedExpandResponseList]): + The words that were expanded, indexed by their initial + character. (-- aip.dev/not-precedent: This is a legacy, + non-standard pattern that violates aip.dev/158. Ordinarily, + this should be a ``repeated`` field, as in + PagedExpandResponse. --) + next_page_token (str): + The next page token. + """ + + @property + def raw_page(self): + return self + + alphabetized: MutableMapping[str, 'PagedExpandResponseList'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='PagedExpandResponseList', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class WaitRequest(proto.Message): + r"""The request for Wait method. + + 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: + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time that this operation will complete. + + This field is a member of `oneof`_ ``end``. + ttl (google.protobuf.duration_pb2.Duration): + The duration of this operation. + + This field is a member of `oneof`_ ``end``. + error (google.rpc.status_pb2.Status): + The error that will be returned by the + server. If this code is specified to be the OK + rpc code, an empty response will be returned. + + This field is a member of `oneof`_ ``response``. + success (google.showcase_v1beta1.types.WaitResponse): + The response to be returned on operation + completion. + + This field is a member of `oneof`_ ``response``. + """ + + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + oneof='end', + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + oneof='end', + message=duration_pb2.Duration, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message=status_pb2.Status, + ) + success: 'WaitResponse' = proto.Field( + proto.MESSAGE, + number=3, + oneof='response', + message='WaitResponse', + ) + + +class WaitResponse(proto.Message): + r"""The result of the Wait operation. + + Attributes: + content (str): + This content of the result. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + + +class WaitMetadata(proto.Message): + r"""The metadata for Wait operation. + + Attributes: + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time that this operation will complete. + """ + + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +class BlockRequest(proto.Message): + r"""The request for Block method. + + 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: + response_delay (google.protobuf.duration_pb2.Duration): + The amount of time to block before returning + a response. + error (google.rpc.status_pb2.Status): + The error that will be returned by the + server. If this code is specified to be the OK + rpc code, an empty response will be returned. + + This field is a member of `oneof`_ ``response``. + success (google.showcase_v1beta1.types.BlockResponse): + The response to be returned that will signify + successful method call. + + This field is a member of `oneof`_ ``response``. + """ + + response_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message=status_pb2.Status, + ) + success: 'BlockResponse' = proto.Field( + proto.MESSAGE, + number=3, + oneof='response', + message='BlockResponse', + ) + + +class BlockResponse(proto.Message): + r"""The response for Block method. + + Attributes: + content (str): + This content can contain anything, the server + will not depend on a value here. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py new file mode 100644 index 000000000000..c2e1346e8f3f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.showcase.v1beta1', + manifest={ + 'User', + 'CreateUserRequest', + 'GetUserRequest', + 'UpdateUserRequest', + 'DeleteUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + }, +) + + +class User(proto.Message): + r"""A user. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The resource name of the user. + display_name (str): + The display_name of the user. + email (str): + The email address of the user. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the user was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The latest timestamp at which the user was + updated. + age (int): + The age of the user in years. + + This field is a member of `oneof`_ ``_age``. + height_feet (float): + The height of the user in feet. + + This field is a member of `oneof`_ ``_height_feet``. + nickname (str): + The nickname of the user. + + (-- aip.dev/not-precedent: An empty string is a valid + nickname. Ordinarily, proto3_optional should not be used on + a ``string`` field. --) + + This field is a member of `oneof`_ ``_nickname``. + enable_notifications (bool): + Enables the receiving of notifications. The default is true + if unset. + + (-- aip.dev/not-precedent: The default for the feature is + true. Ordinarily, the default for a ``bool`` field should be + false. --) + + This field is a member of `oneof`_ ``_enable_notifications``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + email: 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, + ) + age: int = proto.Field( + proto.INT32, + number=6, + optional=True, + ) + height_feet: float = proto.Field( + proto.DOUBLE, + number=7, + optional=True, + ) + nickname: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + enable_notifications: bool = proto.Field( + proto.BOOL, + number=9, + optional=True, + ) + + +class CreateUserRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Identity\CreateUser method. + + Attributes: + user (google.showcase_v1beta1.types.User): + The user to create. + """ + + user: 'User' = proto.Field( + proto.MESSAGE, + number=1, + message='User', + ) + + +class GetUserRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Identity\GetUser method. + + Attributes: + name (str): + The resource name of the requested user. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateUserRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Identity\UpdateUser method. + + Attributes: + user (google.showcase_v1beta1.types.User): + The user to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The field mask to determine which fields are + to be updated. If empty, the server will assume + all fields are to be updated. + """ + + user: 'User' = proto.Field( + proto.MESSAGE, + number=1, + message='User', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteUserRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Identity\DeleteUser method. + + Attributes: + name (str): + The resource name of the user to delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUsersRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Identity\ListUsers method. + + Attributes: + page_size (int): + The maximum number of users to return. Server + may return fewer users than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + The value of + google.showcase.v1beta1.ListUsersResponse.next_page_token + returned from the previous call to + ``google.showcase.v1beta1.Identity\ListUsers`` method. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListUsersResponse(proto.Message): + r"""The response message for the + google.showcase.v1beta1.Identity\ListUsers method. + + Attributes: + users (MutableSequence[google.showcase_v1beta1.types.User]): + The list of users. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + ListUsersRequest.page_token field in the subsequent call to + ``google.showcase.v1beta1.Message\ListUsers`` method to + retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + users: MutableSequence['User'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='User', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py new file mode 100644 index 000000000000..0843ea5da7d1 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py @@ -0,0 +1,668 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.error_details_pb2 as error_details_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.showcase.v1beta1', + manifest={ + 'Room', + 'CreateRoomRequest', + 'GetRoomRequest', + 'UpdateRoomRequest', + 'DeleteRoomRequest', + 'ListRoomsRequest', + 'ListRoomsResponse', + 'Blurb', + 'CreateBlurbRequest', + 'GetBlurbRequest', + 'UpdateBlurbRequest', + 'DeleteBlurbRequest', + 'ListBlurbsRequest', + 'ListBlurbsResponse', + 'SearchBlurbsRequest', + 'SearchBlurbsMetadata', + 'SearchBlurbsResponse', + 'StreamBlurbsRequest', + 'StreamBlurbsResponse', + 'SendBlurbsResponse', + 'ConnectRequest', + }, +) + + +class Room(proto.Message): + r"""A chat room. + + Attributes: + name (str): + The resource name of the chat room. + display_name (str): + The human readable name of the chat room. + description (str): + The description of the chat room. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the room was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The latest timestamp at which the room was + updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class CreateRoomRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\CreateRoom method. + + Attributes: + room (google.showcase_v1beta1.types.Room): + The room to create. + """ + + room: 'Room' = proto.Field( + proto.MESSAGE, + number=1, + message='Room', + ) + + +class GetRoomRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\GetRoom method. + + Attributes: + name (str): + The resource name of the requested room. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateRoomRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\UpdateRoom method. + + Attributes: + room (google.showcase_v1beta1.types.Room): + The room to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The field mask to determine which fields are + to be updated. If empty, the server will assume + all fields are to be updated. + """ + + room: 'Room' = proto.Field( + proto.MESSAGE, + number=1, + message='Room', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteRoomRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\DeleteRoom method. + + Attributes: + name (str): + The resource name of the requested room. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRoomsRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\ListRooms method. + + Attributes: + page_size (int): + The maximum number of rooms return. Server + may return fewer rooms than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + The value of + google.showcase.v1beta1.ListRoomsResponse.next_page_token + returned from the previous call to + ``google.showcase.v1beta1.Messaging\ListRooms`` method. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListRoomsResponse(proto.Message): + r"""The response message for the + google.showcase.v1beta1.Messaging\ListRooms method. + + Attributes: + rooms (MutableSequence[google.showcase_v1beta1.types.Room]): + The list of rooms. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + ListRoomsRequest.page_token field in the subsequent call to + ``google.showcase.v1beta1.Messaging\ListRooms`` method to + retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + rooms: MutableSequence['Room'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Room', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Blurb(proto.Message): + r"""This protocol buffer message represents a blurb sent to a + chat room or posted on a user profile. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The resource name of the chat room. + user (str): + The resource name of the blurb's author. + text (str): + The textual content of this blurb. + + This field is a member of `oneof`_ ``content``. + image (bytes): + The image content of this blurb. + + This field is a member of `oneof`_ ``content``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the blurb was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The latest timestamp at which the blurb was + updated. + legacy_room_id (str): + The legacy id of the room. This field is used to signal the + use of the compound resource pattern + ``rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}`` + + This field is a member of `oneof`_ ``legacy_id``. + legacy_user_id (str): + The legacy id of the user. This field is used to signal the + use of the compound resource pattern + ``users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}`` + + This field is a member of `oneof`_ ``legacy_id``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user: str = proto.Field( + proto.STRING, + number=2, + ) + text: str = proto.Field( + proto.STRING, + number=3, + oneof='content', + ) + image: bytes = proto.Field( + proto.BYTES, + number=4, + oneof='content', + ) + 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, + ) + legacy_room_id: str = proto.Field( + proto.STRING, + number=7, + oneof='legacy_id', + ) + legacy_user_id: str = proto.Field( + proto.STRING, + number=8, + oneof='legacy_id', + ) + + +class CreateBlurbRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\CreateBlurb method. + + Attributes: + parent (str): + The resource name of the chat room or user + profile that this blurb will be tied to. + blurb (google.showcase_v1beta1.types.Blurb): + The blurb to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + blurb: 'Blurb' = proto.Field( + proto.MESSAGE, + number=2, + message='Blurb', + ) + + +class GetBlurbRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\GetBlurb method. + + Attributes: + name (str): + The resource name of the requested blurb. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateBlurbRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\UpdateBlurb method. + + Attributes: + blurb (google.showcase_v1beta1.types.Blurb): + The blurb to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The field mask to determine wich fields are + to be updated. If empty, the server will assume + all fields are to be updated. + """ + + blurb: 'Blurb' = proto.Field( + proto.MESSAGE, + number=1, + message='Blurb', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteBlurbRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\DeleteBlurb method. + + Attributes: + name (str): + The resource name of the requested blurb. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBlurbsRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\ListBlurbs method. + + Attributes: + parent (str): + The resource name of the requested room or + profile whos blurbs to list. + page_size (int): + The maximum number of blurbs to return. + Server may return fewer blurbs than requested. + If unspecified, server will pick an appropriate + default. + page_token (str): + The value of + google.showcase.v1beta1.ListBlurbsResponse.next_page_token + returned from the previous call to + ``google.showcase.v1beta1.Messaging\ListBlurbs`` method. + """ + + 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 ListBlurbsResponse(proto.Message): + r"""The response message for the + google.showcase.v1beta1.Messaging\ListBlurbs method. + + Attributes: + blurbs (MutableSequence[google.showcase_v1beta1.types.Blurb]): + The list of blurbs. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + ListBlurbsRequest.page_token field in the subsequent call to + ``google.showcase.v1beta1.Blurb\ListBlurbs`` method to + retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + blurbs: MutableSequence['Blurb'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Blurb', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchBlurbsRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\SearchBlurbs method. + + Attributes: + query (str): + The query used to search for blurbs + containing to words of this string. Only posts + that contain an exact match of a queried word + will be returned. + parent (str): + The rooms or profiles to search. If unset, ``SearchBlurbs`` + will search all rooms and all profiles. + page_size (int): + The maximum number of blurbs return. Server + may return fewer blurbs than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + The value of + google.showcase.v1beta1.SearchBlurbsResponse.next_page_token + returned from the previous call to + ``google.showcase.v1beta1.Messaging\SearchBlurbs`` method. + """ + + query: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchBlurbsMetadata(proto.Message): + r"""The operation metadata message for the + google.showcase.v1beta1.Messaging\SearchBlurbs method. + + Attributes: + retry_info (google.rpc.error_details_pb2.RetryInfo): + This signals to the client when to next poll + for response. + """ + + retry_info: error_details_pb2.RetryInfo = proto.Field( + proto.MESSAGE, + number=1, + message=error_details_pb2.RetryInfo, + ) + + +class SearchBlurbsResponse(proto.Message): + r"""The operation response message for the + google.showcase.v1beta1.Messaging\SearchBlurbs method. + + Attributes: + blurbs (MutableSequence[google.showcase_v1beta1.types.Blurb]): + Blurbs that matched the search query. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + SearchBlurbsRequest.page_token field in the subsequent call + to ``google.showcase.v1beta1.Blurb\SearchBlurbs`` method to + retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + blurbs: MutableSequence['Blurb'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Blurb', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StreamBlurbsRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\StreamBlurbs method. + + Attributes: + name (str): + The resource name of a chat room or user + profile whose blurbs to stream. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which this stream will close. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class StreamBlurbsResponse(proto.Message): + r"""The response message for the + google.showcase.v1beta1.Messaging\StreamBlurbs method. + + Attributes: + blurb (google.showcase_v1beta1.types.Blurb): + The blurb that was either created, updated, + or deleted. + action (google.showcase_v1beta1.types.StreamBlurbsResponse.Action): + The action that triggered the blurb to be + returned. + """ + class Action(proto.Enum): + r"""The action that triggered the blurb to be returned. + + Values: + ACTION_UNSPECIFIED (0): + No description available. + CREATE (1): + Specifies that the blurb was created. + UPDATE (2): + Specifies that the blurb was updated. + DELETE (3): + Specifies that the blurb was deleted. + """ + ACTION_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + + blurb: 'Blurb' = proto.Field( + proto.MESSAGE, + number=1, + message='Blurb', + ) + action: Action = proto.Field( + proto.ENUM, + number=2, + enum=Action, + ) + + +class SendBlurbsResponse(proto.Message): + r"""The response message for the + google.showcase.v1beta1.Messaging\SendBlurbs method. + + Attributes: + names (MutableSequence[str]): + The names of successful blurb creations. + """ + + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class ConnectRequest(proto.Message): + r"""The request message for the + google.showcase.v1beta1.Messaging\Connect method. + + 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: + config (google.showcase_v1beta1.types.ConnectRequest.ConnectConfig): + Provides information that specifies how to process + subsequent requests. The first ``ConnectRequest`` message + must contain a ``config`` message. + + This field is a member of `oneof`_ ``request``. + blurb (google.showcase_v1beta1.types.Blurb): + The blurb to be created. + + This field is a member of `oneof`_ ``request``. + """ + + class ConnectConfig(proto.Message): + r""" + + Attributes: + parent (str): + The room or profile to follow and create + messages for. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + config: ConnectConfig = proto.Field( + proto.MESSAGE, + number=1, + oneof='request', + message=ConnectConfig, + ) + blurb: 'Blurb' = proto.Field( + proto.MESSAGE, + number=2, + oneof='request', + message='Blurb', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/gapic-generator/generated_showcase/noxfile.py b/packages/gapic-generator/generated_showcase/noxfile.py new file mode 100644 index 000000000000..0bd125534ee2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/noxfile.py @@ -0,0 +1,635 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +from typing import Dict, List +import warnings + +import nox + +RUFF_VERSION = "ruff==0.14.14" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +# Add samples to the list of directories to format if the directory exists. +if os.path.isdir("samples"): + LINT_PATHS.append("samples") + +ALL_PYTHON = [ + "3.10", + "3.11", + "3.12", + "3.13", + "3.14", + "3.15", +] + +DEFAULT_PYTHON_VERSION = "3.14" + +PREVIEW_PYTHON_VERSION = "3.15" + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() +# Path to the centralized mypy configuration file at the repository root. +# Search upwards to support running nox from both monorepo packages and integration test goldens. +MYPY_CONFIG_FILE = next( + (str(p / "mypy.ini") for p in CURRENT_DIRECTORY.parents if (p / "mypy.ini").exists()), + str(CURRENT_DIRECTORY.parent.parent / "mypy.ini"), +) + +if (CURRENT_DIRECTORY / "testing").exists(): + LOWER_BOUND_CONSTRAINTS_FILE = ( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt" + ) +else: + LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-showcase" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ALL_PYTHON +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2579): + # use the latest version of mypy + session.install( + "mypy<1.16.0", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + f"--config-file={MYPY_CONFIG_FILE}", + "-p", + "google", + "--check-untyped-defs", + *session.posargs, + ) + + +@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 lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", RUFF_VERSION) + + # 2. Check formatting + session.run( + "ruff", "format", + "--check", + f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", + "--line-length=88", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """(Deprecated) Legacy session. Please use 'nox -s format'.""" + session.log("WARNING: The 'blacken' session is deprecated and will be removed in a future release. Please use 'nox -s format' in the future.") + + # Just run the ruff formatter (keeping legacy behavior of only formatting, not sorting imports) + session.install(RUFF_VERSION) + session.run( + "ruff", "format", + f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", + "--line-length=88", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run ruff to sort imports and format code. + """ + # 1. Install ruff (skipped automatically if you run with --no-venv) + session.install(RUFF_VERSION) + + # 2. Run Ruff to fix imports + # check --select I: Enables strict import sorting + # --fix: Applies the changes automatically + session.run( + "ruff", "check", + "--select", "I", + "--fix", + f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", + "--line-length=88", # Standard Black line length + *LINT_PATHS, + ) + + # 3. Run Ruff to format code + session.run( + "ruff", "format", + f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", + "--line-length=88", # Standard Black line length + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + if session.python >= "3.12": + session.install("--pre", "grpcio>=1.75.1") + else: + session.install("--pre", "grpcio<=1.62.2") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-b", "html", # builder + "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory + # paths to build: + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=PREVIEW_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all 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 + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio>=1.75.1" if session.python >= "3.12" else "grpcio<=1.62.2", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + deps_dir = CURRENT_DIRECTORY.parent + while deps_dir.name != "packages" and deps_dir.parent != deps_dir: + deps_dir = deps_dir.parent + + # Extract the base package name, safely ignoring version bounds and spaces + # (e.g., "grpcio>=1.75.1" becomes "grpcio") + parsed_deps = { + dep: re.match(r"^([a-zA-Z0-9_-]+)", dep).group(1) + for dep in prerel_deps + } + + # Dynamically sort local packages vs PyPI dependencies + local_paths = [] + pypi_deps = [] + + for dep, pkg_name in parsed_deps.items(): + if (deps_dir / pkg_name).exists(): + local_paths.append(str(deps_dir / pkg_name)) + else: + pypi_deps.append(dep) + + # Batch pip installations to avoid sequential overhead + if local_paths: + session.install(*local_paths, "--no-deps", "--ignore-installed") + if pypi_deps: + session.install(*pypi_deps, "--pre", "--no-deps", "--ignore-installed") + + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + # Reuse the parsed names for logging and version verification + for dep, pkg_name in parsed_deps.items(): + print(f"Installed {dep}") + version_namespace = package_namespaces.get(pkg_name) + + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=PREVIEW_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all 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 + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "proto-plus", + ] + + deps_dir = CURRENT_DIRECTORY.parent + while deps_dir.name != "packages" and deps_dir.parent != deps_dir: + deps_dir = deps_dir.parent + + # Batch the pip installation to avoid sequential overhead + dep_paths = [str(deps_dir / dep) for dep in core_dependencies_from_source] + + session.install(*dep_paths, "--no-deps", "--ignore-installed") + print(f"Installed {', '.join(core_dependencies_from_source)} locally from {deps_dir}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py new file mode 100644 index 000000000000..ccfa4c54c81e --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Block +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Block_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_block(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.BlockRequest( + ) + + # Make the request + response = await client.block(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Block_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py new file mode 100644 index 000000000000..793a37968c5f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Block +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Block_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_block(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.BlockRequest( + ) + + # Make the request + response = client.block(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Block_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py new file mode 100644 index 000000000000..6e52dedc77f1 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Chat +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Chat_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_chat(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.chat(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Chat_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py new file mode 100644 index 000000000000..8b6916a40d86 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Chat +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Chat_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_chat(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.chat(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Chat_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py new file mode 100644 index 000000000000..f27f28952799 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Collect +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Collect_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_collect(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = await client.collect(requests=request_generator()) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Collect_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py new file mode 100644 index 000000000000..88d9cc06d0ac --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Collect +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Collect_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_collect(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.EchoRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = client.collect(requests=request_generator()) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Collect_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py new file mode 100644 index 000000000000..8d2939515521 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Echo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Echo_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_echo(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # Make the request + response = await client.echo(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Echo_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py new file mode 100644 index 000000000000..61d1cedb770f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EchoErrorDetails +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_echo_error_details(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoErrorDetailsRequest( + ) + + # Make the request + response = await client.echo_error_details(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py new file mode 100644 index 000000000000..80d6ab4e0bb3 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EchoErrorDetails +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_echo_error_details(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoErrorDetailsRequest( + ) + + # Make the request + response = client.echo_error_details(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py new file mode 100644 index 000000000000..8be25fdad6aa --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Echo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Echo_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_echo(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.EchoRequest( + content="content_value", + ) + + # Make the request + response = client.echo(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Echo_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py new file mode 100644 index 000000000000..577d5ad90ef4 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Expand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Expand_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_expand(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ExpandRequest( + ) + + # Make the request + stream = await client.expand(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Expand_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py new file mode 100644 index 000000000000..e7e36ecd9c26 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Expand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Expand_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_expand(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ExpandRequest( + ) + + # Make the request + stream = client.expand(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Expand_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py new file mode 100644 index 000000000000..71b07b122d22 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PagedExpand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_PagedExpand_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_paged_expand(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_PagedExpand_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py new file mode 100644 index 000000000000..8f6dba9bdd67 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PagedExpandLegacy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_paged_expand_legacy(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandLegacyRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py new file mode 100644 index 000000000000..fb80b5a96ee9 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PagedExpandLegacyMapped +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_paged_expand_legacy_mapped(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy_mapped(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py new file mode 100644 index 000000000000..4eb8314f58f1 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PagedExpandLegacyMapped +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_paged_expand_legacy_mapped(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy_mapped(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py new file mode 100644 index 000000000000..8f2706bbdcfa --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PagedExpandLegacy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_paged_expand_legacy(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandLegacyRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand_legacy(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py new file mode 100644 index 000000000000..67bd7840c35f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PagedExpand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_PagedExpand_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_paged_expand(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.PagedExpandRequest( + content="content_value", + ) + + # Make the request + page_result = client.paged_expand(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_PagedExpand_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py new file mode 100644 index 000000000000..4414bf510efb --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Wait +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Wait_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_wait(): + # Create a client + client = showcase_v1beta1.EchoAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.WaitRequest( + ) + + # Make the request + operation = await client.wait(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Wait_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py new file mode 100644 index 000000000000..4dc408d6ae76 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Wait +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Echo_Wait_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_wait(): + # Create a client + client = showcase_v1beta1.EchoClient() + + # Initialize request argument(s) + request = showcase_v1beta1.WaitRequest( + ) + + # Make the request + operation = client.wait(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Echo_Wait_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py new file mode 100644 index 000000000000..6630faac2b2d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_CreateUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_create_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateUserRequest( + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_CreateUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py new file mode 100644 index 000000000000..249cfce8edb8 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_CreateUser_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_create_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateUserRequest( + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_CreateUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py new file mode 100644 index 000000000000..e263fb8eeaa1 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_DeleteUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_delete_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + +# [END localhost:7469_v1beta1_generated_Identity_DeleteUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py new file mode 100644 index 000000000000..463d7bc7f745 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_DeleteUser_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_delete_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + +# [END localhost:7469_v1beta1_generated_Identity_DeleteUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py new file mode 100644 index 000000000000..38a3a2d62d86 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_GetUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_get_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_GetUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py new file mode 100644 index 000000000000..bf9a19b673ff --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_GetUser_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_get_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_GetUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py new file mode 100644 index 000000000000..5464905cbeb2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_ListUsers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_list_users(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListUsersRequest( + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_ListUsers_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py new file mode 100644 index 000000000000..91524f9f68c2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_ListUsers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_list_users(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListUsersRequest( + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_ListUsers_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py new file mode 100644 index 000000000000..2a8e502c902e --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_UpdateUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_update_user(): + # Create a client + client = showcase_v1beta1.IdentityAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_UpdateUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py new file mode 100644 index 000000000000..ba15ed5eec2c --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Identity_UpdateUser_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_update_user(): + # Create a client + client = showcase_v1beta1.IdentityClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Identity_UpdateUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py new file mode 100644 index 000000000000..48dac27bf485 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Connect +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_Connect_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_connect(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ConnectRequest( + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.ConnectRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.connect(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_Connect_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py new file mode 100644 index 000000000000..d9e5f9c128d0 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Connect +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_Connect_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_connect(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ConnectRequest( + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.ConnectRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.connect(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_Connect_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py new file mode 100644 index 000000000000..93e4bc2186f7 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_CreateBlurb_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_create_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_blurb(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_CreateBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py new file mode 100644 index 000000000000..0300a179f538 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_CreateBlurb_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_create_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_blurb(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_CreateBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py new file mode 100644 index 000000000000..6d68319ce5ce --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_CreateRoom_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_create_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateRoomRequest( + ) + + # Make the request + response = await client.create_room(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_CreateRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py new file mode 100644 index 000000000000..0b82661bd0c7 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_CreateRoom_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_create_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateRoomRequest( + ) + + # Make the request + response = client.create_room(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_CreateRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py new file mode 100644 index 000000000000..85defa14ff6f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_delete_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteBlurbRequest( + name="name_value", + ) + + # Make the request + await client.delete_blurb(request=request) + + +# [END localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py new file mode 100644 index 000000000000..4076b61b058a --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_delete_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteBlurbRequest( + name="name_value", + ) + + # Make the request + client.delete_blurb(request=request) + + +# [END localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py new file mode 100644 index 000000000000..45d408b11548 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_DeleteRoom_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_delete_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteRoomRequest( + name="name_value", + ) + + # Make the request + await client.delete_room(request=request) + + +# [END localhost:7469_v1beta1_generated_Messaging_DeleteRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py new file mode 100644 index 000000000000..780e34918d10 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_DeleteRoom_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_delete_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.DeleteRoomRequest( + name="name_value", + ) + + # Make the request + client.delete_room(request=request) + + +# [END localhost:7469_v1beta1_generated_Messaging_DeleteRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py new file mode 100644 index 000000000000..8e702f32fa7d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_GetBlurb_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_get_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetBlurbRequest( + name="name_value", + ) + + # Make the request + response = await client.get_blurb(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_GetBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py new file mode 100644 index 000000000000..a6445d43844b --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_GetBlurb_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_get_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetBlurbRequest( + name="name_value", + ) + + # Make the request + response = client.get_blurb(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_GetBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py new file mode 100644 index 000000000000..4163de2cb223 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_GetRoom_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_get_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetRoomRequest( + name="name_value", + ) + + # Make the request + response = await client.get_room(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_GetRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py new file mode 100644 index 000000000000..cc44db0dc51f --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_GetRoom_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_get_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.GetRoomRequest( + name="name_value", + ) + + # Make the request + response = client.get_room(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_GetRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py new file mode 100644 index 000000000000..95751b3924b0 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_ListBlurbs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_list_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListBlurbsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_blurbs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_ListBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py new file mode 100644 index 000000000000..8089c0f6e2b2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_ListBlurbs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_list_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListBlurbsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_blurbs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_ListBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py new file mode 100644 index 000000000000..8918c51b6496 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRooms +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_ListRooms_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_list_rooms(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListRoomsRequest( + ) + + # Make the request + page_result = client.list_rooms(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_ListRooms_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py new file mode 100644 index 000000000000..86d8a78152a2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRooms +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_ListRooms_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_list_rooms(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.ListRoomsRequest( + ) + + # Make the request + page_result = client.list_rooms(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_ListRooms_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py new file mode 100644 index 000000000000..d73d46d571df --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_search_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.SearchBlurbsRequest( + query="query_value", + ) + + # Make the request + operation = await client.search_blurbs(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py new file mode 100644 index 000000000000..0f3a9fee5b3d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_search_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.SearchBlurbsRequest( + query="query_value", + ) + + # Make the request + operation = client.search_blurbs(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py new file mode 100644 index 000000000000..b7f2a6591356 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_SendBlurbs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_send_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.CreateBlurbRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = await client.send_blurbs(requests=request_generator()) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_SendBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py new file mode 100644 index 000000000000..8f899913c3a6 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_SendBlurbs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_send_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.CreateBlurbRequest( + parent="parent_value", + ) + + # This method expects an iterator which contains + # 'showcase_v1beta1.CreateBlurbRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + response = client.send_blurbs(requests=request_generator()) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_SendBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py new file mode 100644 index 000000000000..b787a1e06bc0 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StreamBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_stream_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.StreamBlurbsRequest( + name="name_value", + ) + + # Make the request + stream = await client.stream_blurbs(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py new file mode 100644 index 000000000000..cf1f64485c01 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StreamBlurbs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_stream_blurbs(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.StreamBlurbsRequest( + name="name_value", + ) + + # Make the request + stream = client.stream_blurbs(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py new file mode 100644 index 000000000000..b5448a10ed2e --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_update_blurb(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateBlurbRequest( + ) + + # Make the request + response = await client.update_blurb(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py new file mode 100644 index 000000000000..4e774d3135a3 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBlurb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_update_blurb(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateBlurbRequest( + ) + + # Make the request + response = client.update_blurb(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py new file mode 100644 index 000000000000..c37973a377a4 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_UpdateRoom_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +async def sample_update_room(): + # Create a client + client = showcase_v1beta1.MessagingAsyncClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateRoomRequest( + ) + + # Make the request + response = await client.update_room(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_UpdateRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py new file mode 100644 index 000000000000..7eb0773a95c6 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRoom +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-showcase + + +# [START localhost:7469_v1beta1_generated_Messaging_UpdateRoom_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google import showcase_v1beta1 + + +def sample_update_room(): + # Create a client + client = showcase_v1beta1.MessagingClient() + + # Initialize request argument(s) + request = showcase_v1beta1.UpdateRoomRequest( + ) + + # Make the request + response = client.update_room(request=request) + + # Handle the response + print(response) + +# [END localhost:7469_v1beta1_generated_Messaging_UpdateRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json b/packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json new file mode 100644 index 000000000000..d5032e271d38 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json @@ -0,0 +1,4618 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.showcase.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-showcase", + "version": "0.0.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.block", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Block", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Block" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.BlockRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.BlockResponse", + "shortName": "block" + }, + "description": "Sample for Block", + "file": "localhost:7469_v1beta1_generated_echo_block_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Block_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_block_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.block", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Block", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Block" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.BlockRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.BlockResponse", + "shortName": "block" + }, + "description": "Sample for Block", + "file": "localhost:7469_v1beta1_generated_echo_block_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Block_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_block_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.chat", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Chat", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Chat" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", + "shortName": "chat" + }, + "description": "Sample for Chat", + "file": "localhost:7469_v1beta1_generated_echo_chat_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Chat_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_chat_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.chat", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Chat", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Chat" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", + "shortName": "chat" + }, + "description": "Sample for Chat", + "file": "localhost:7469_v1beta1_generated_echo_chat_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Chat_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_chat_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.collect", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Collect", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Collect" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.EchoResponse", + "shortName": "collect" + }, + "description": "Sample for Collect", + "file": "localhost:7469_v1beta1_generated_echo_collect_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Collect_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_collect_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.collect", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Collect", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Collect" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.EchoResponse", + "shortName": "collect" + }, + "description": "Sample for Collect", + "file": "localhost:7469_v1beta1_generated_echo_collect_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Collect_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_collect_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.echo_error_details", + "method": { + "fullName": "google.showcase.v1beta1.Echo.EchoErrorDetails", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "EchoErrorDetails" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.EchoErrorDetailsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.EchoErrorDetailsResponse", + "shortName": "echo_error_details" + }, + "description": "Sample for EchoErrorDetails", + "file": "localhost:7469_v1beta1_generated_echo_echo_error_details_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_echo_error_details_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.echo_error_details", + "method": { + "fullName": "google.showcase.v1beta1.Echo.EchoErrorDetails", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "EchoErrorDetails" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.EchoErrorDetailsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.EchoErrorDetailsResponse", + "shortName": "echo_error_details" + }, + "description": "Sample for EchoErrorDetails", + "file": "localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.echo", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Echo", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Echo" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.EchoRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.EchoResponse", + "shortName": "echo" + }, + "description": "Sample for Echo", + "file": "localhost:7469_v1beta1_generated_echo_echo_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Echo_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": "localhost:7469_v1beta1_generated_echo_echo_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.echo", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Echo", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Echo" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.EchoRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.EchoResponse", + "shortName": "echo" + }, + "description": "Sample for Echo", + "file": "localhost:7469_v1beta1_generated_echo_echo_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Echo_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": "localhost:7469_v1beta1_generated_echo_echo_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.expand", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Expand", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Expand" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ExpandRequest" + }, + { + "name": "content", + "type": "str" + }, + { + "name": "error", + "type": "google.rpc.status_pb2.Status" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", + "shortName": "expand" + }, + "description": "Sample for Expand", + "file": "localhost:7469_v1beta1_generated_echo_expand_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Expand_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_expand_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.expand", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Expand", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Expand" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ExpandRequest" + }, + { + "name": "content", + "type": "str" + }, + { + "name": "error", + "type": "google.rpc.status_pb2.Status" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", + "shortName": "expand" + }, + "description": "Sample for Expand", + "file": "localhost:7469_v1beta1_generated_echo_expand_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Expand_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_echo_expand_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.paged_expand_legacy_mapped", + "method": { + "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacyMapped", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "PagedExpandLegacyMapped" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.PagedExpandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedAsyncPager", + "shortName": "paged_expand_legacy_mapped" + }, + "description": "Sample for PagedExpandLegacyMapped", + "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.paged_expand_legacy_mapped", + "method": { + "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacyMapped", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "PagedExpandLegacyMapped" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.PagedExpandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedPager", + "shortName": "paged_expand_legacy_mapped" + }, + "description": "Sample for PagedExpandLegacyMapped", + "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.paged_expand_legacy", + "method": { + "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacy", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "PagedExpandLegacy" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.PagedExpandLegacyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyAsyncPager", + "shortName": "paged_expand_legacy" + }, + "description": "Sample for PagedExpandLegacy", + "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.paged_expand_legacy", + "method": { + "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacy", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "PagedExpandLegacy" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.PagedExpandLegacyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyPager", + "shortName": "paged_expand_legacy" + }, + "description": "Sample for PagedExpandLegacy", + "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.paged_expand", + "method": { + "fullName": "google.showcase.v1beta1.Echo.PagedExpand", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "PagedExpand" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.PagedExpandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandAsyncPager", + "shortName": "paged_expand" + }, + "description": "Sample for PagedExpand", + "file": "localhost:7469_v1beta1_generated_echo_paged_expand_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpand_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": "localhost:7469_v1beta1_generated_echo_paged_expand_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.paged_expand", + "method": { + "fullName": "google.showcase.v1beta1.Echo.PagedExpand", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "PagedExpand" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.PagedExpandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandPager", + "shortName": "paged_expand" + }, + "description": "Sample for PagedExpand", + "file": "localhost:7469_v1beta1_generated_echo_paged_expand_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpand_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": "localhost:7469_v1beta1_generated_echo_paged_expand_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.EchoAsyncClient", + "shortName": "EchoAsyncClient" + }, + "fullName": "google.showcase_v1beta1.EchoAsyncClient.wait", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Wait", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Wait" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.WaitRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "wait" + }, + "description": "Sample for Wait", + "file": "localhost:7469_v1beta1_generated_echo_wait_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Wait_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": "localhost:7469_v1beta1_generated_echo_wait_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.EchoClient", + "shortName": "EchoClient" + }, + "fullName": "google.showcase_v1beta1.EchoClient.wait", + "method": { + "fullName": "google.showcase.v1beta1.Echo.Wait", + "service": { + "fullName": "google.showcase.v1beta1.Echo", + "shortName": "Echo" + }, + "shortName": "Wait" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.WaitRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "wait" + }, + "description": "Sample for Wait", + "file": "localhost:7469_v1beta1_generated_echo_wait_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Echo_Wait_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": "localhost:7469_v1beta1_generated_echo_wait_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.IdentityAsyncClient", + "shortName": "IdentityAsyncClient" + }, + "fullName": "google.showcase_v1beta1.IdentityAsyncClient.create_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.CreateUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.CreateUserRequest" + }, + { + "name": "display_name", + "type": "str" + }, + { + "name": "email", + "type": "str" + }, + { + "name": "age", + "type": "int" + }, + { + "name": "nickname", + "type": "str" + }, + { + "name": "enable_notifications", + "type": "bool" + }, + { + "name": "height_feet", + "type": "float" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "localhost:7469_v1beta1_generated_identity_create_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_CreateUser_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_create_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.IdentityClient", + "shortName": "IdentityClient" + }, + "fullName": "google.showcase_v1beta1.IdentityClient.create_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.CreateUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.CreateUserRequest" + }, + { + "name": "display_name", + "type": "str" + }, + { + "name": "email", + "type": "str" + }, + { + "name": "age", + "type": "int" + }, + { + "name": "nickname", + "type": "str" + }, + { + "name": "enable_notifications", + "type": "bool" + }, + { + "name": "height_feet", + "type": "float" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "localhost:7469_v1beta1_generated_identity_create_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_CreateUser_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_create_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.IdentityAsyncClient", + "shortName": "IdentityAsyncClient" + }, + "fullName": "google.showcase_v1beta1.IdentityAsyncClient.delete_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.DeleteUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "localhost:7469_v1beta1_generated_identity_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_DeleteUser_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.IdentityClient", + "shortName": "IdentityClient" + }, + "fullName": "google.showcase_v1beta1.IdentityClient.delete_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.DeleteUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "localhost:7469_v1beta1_generated_identity_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_DeleteUser_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.IdentityAsyncClient", + "shortName": "IdentityAsyncClient" + }, + "fullName": "google.showcase_v1beta1.IdentityAsyncClient.get_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.GetUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.GetUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "localhost:7469_v1beta1_generated_identity_get_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_GetUser_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": "localhost:7469_v1beta1_generated_identity_get_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.IdentityClient", + "shortName": "IdentityClient" + }, + "fullName": "google.showcase_v1beta1.IdentityClient.get_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.GetUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.GetUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "localhost:7469_v1beta1_generated_identity_get_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_GetUser_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": "localhost:7469_v1beta1_generated_identity_get_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.IdentityAsyncClient", + "shortName": "IdentityAsyncClient" + }, + "fullName": "google.showcase_v1beta1.IdentityAsyncClient.list_users", + "method": { + "fullName": "google.showcase.v1beta1.Identity.ListUsers", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ListUsersRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.identity.pagers.ListUsersAsyncPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "localhost:7469_v1beta1_generated_identity_list_users_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_ListUsers_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_list_users_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.IdentityClient", + "shortName": "IdentityClient" + }, + "fullName": "google.showcase_v1beta1.IdentityClient.list_users", + "method": { + "fullName": "google.showcase.v1beta1.Identity.ListUsers", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ListUsersRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.identity.pagers.ListUsersPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "localhost:7469_v1beta1_generated_identity_list_users_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_ListUsers_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_list_users_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.IdentityAsyncClient", + "shortName": "IdentityAsyncClient" + }, + "fullName": "google.showcase_v1beta1.IdentityAsyncClient.update_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.UpdateUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.UpdateUserRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "localhost:7469_v1beta1_generated_identity_update_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_UpdateUser_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_update_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.IdentityClient", + "shortName": "IdentityClient" + }, + "fullName": "google.showcase_v1beta1.IdentityClient.update_user", + "method": { + "fullName": "google.showcase.v1beta1.Identity.UpdateUser", + "service": { + "fullName": "google.showcase.v1beta1.Identity", + "shortName": "Identity" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.UpdateUserRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "localhost:7469_v1beta1_generated_identity_update_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Identity_UpdateUser_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_identity_update_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.connect", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.Connect", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "Connect" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.ConnectRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", + "shortName": "connect" + }, + "description": "Sample for Connect", + "file": "localhost:7469_v1beta1_generated_messaging_connect_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_Connect_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_connect_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.connect", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.Connect", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "Connect" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.ConnectRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", + "shortName": "connect" + }, + "description": "Sample for Connect", + "file": "localhost:7469_v1beta1_generated_messaging_connect_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_Connect_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_connect_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.create_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.CreateBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "CreateBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.CreateBlurbRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "str" + }, + { + "name": "text", + "type": "str" + }, + { + "name": "image", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Blurb", + "shortName": "create_blurb" + }, + "description": "Sample for CreateBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_create_blurb_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateBlurb_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": "localhost:7469_v1beta1_generated_messaging_create_blurb_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.create_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.CreateBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "CreateBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.CreateBlurbRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "str" + }, + { + "name": "text", + "type": "str" + }, + { + "name": "image", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Blurb", + "shortName": "create_blurb" + }, + "description": "Sample for CreateBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateBlurb_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": "localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.create_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.CreateRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "CreateRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.CreateRoomRequest" + }, + { + "name": "display_name", + "type": "str" + }, + { + "name": "description", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Room", + "shortName": "create_room" + }, + "description": "Sample for CreateRoom", + "file": "localhost:7469_v1beta1_generated_messaging_create_room_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateRoom_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_create_room_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.create_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.CreateRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "CreateRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.CreateRoomRequest" + }, + { + "name": "display_name", + "type": "str" + }, + { + "name": "description", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Room", + "shortName": "create_room" + }, + "description": "Sample for CreateRoom", + "file": "localhost:7469_v1beta1_generated_messaging_create_room_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateRoom_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_create_room_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.delete_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.DeleteBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "DeleteBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.DeleteBlurbRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_blurb" + }, + "description": "Sample for DeleteBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.delete_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.DeleteBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "DeleteBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.DeleteBlurbRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_blurb" + }, + "description": "Sample for DeleteBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.delete_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.DeleteRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "DeleteRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.DeleteRoomRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_room" + }, + "description": "Sample for DeleteRoom", + "file": "localhost:7469_v1beta1_generated_messaging_delete_room_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteRoom_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_delete_room_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.delete_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.DeleteRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "DeleteRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.DeleteRoomRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_room" + }, + "description": "Sample for DeleteRoom", + "file": "localhost:7469_v1beta1_generated_messaging_delete_room_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteRoom_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_delete_room_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.get_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.GetBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "GetBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.GetBlurbRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Blurb", + "shortName": "get_blurb" + }, + "description": "Sample for GetBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_get_blurb_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetBlurb_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": "localhost:7469_v1beta1_generated_messaging_get_blurb_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.get_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.GetBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "GetBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.GetBlurbRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Blurb", + "shortName": "get_blurb" + }, + "description": "Sample for GetBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetBlurb_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": "localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.get_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.GetRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "GetRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.GetRoomRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Room", + "shortName": "get_room" + }, + "description": "Sample for GetRoom", + "file": "localhost:7469_v1beta1_generated_messaging_get_room_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetRoom_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": "localhost:7469_v1beta1_generated_messaging_get_room_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.get_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.GetRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "GetRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.GetRoomRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Room", + "shortName": "get_room" + }, + "description": "Sample for GetRoom", + "file": "localhost:7469_v1beta1_generated_messaging_get_room_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetRoom_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": "localhost:7469_v1beta1_generated_messaging_get_room_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.list_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.ListBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "ListBlurbs" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ListBlurbsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListBlurbsAsyncPager", + "shortName": "list_blurbs" + }, + "description": "Sample for ListBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListBlurbs_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": "localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.list_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.ListBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "ListBlurbs" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ListBlurbsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListBlurbsPager", + "shortName": "list_blurbs" + }, + "description": "Sample for ListBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListBlurbs_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": "localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.list_rooms", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.ListRooms", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "ListRooms" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ListRoomsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListRoomsAsyncPager", + "shortName": "list_rooms" + }, + "description": "Sample for ListRooms", + "file": "localhost:7469_v1beta1_generated_messaging_list_rooms_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListRooms_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_list_rooms_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.list_rooms", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.ListRooms", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "ListRooms" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.ListRoomsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListRoomsPager", + "shortName": "list_rooms" + }, + "description": "Sample for ListRooms", + "file": "localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListRooms_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.search_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.SearchBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "SearchBlurbs" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.SearchBlurbsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "search_blurbs" + }, + "description": "Sample for SearchBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_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": "localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.search_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.SearchBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "SearchBlurbs" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.SearchBlurbsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "search_blurbs" + }, + "description": "Sample for SearchBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_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": "localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.send_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.SendBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "SendBlurbs" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.CreateBlurbRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.SendBlurbsResponse", + "shortName": "send_blurbs" + }, + "description": "Sample for SendBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_SendBlurbs_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.send_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.SendBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "SendBlurbs" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.showcase_v1beta1.types.CreateBlurbRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.SendBlurbsResponse", + "shortName": "send_blurbs" + }, + "description": "Sample for SendBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_SendBlurbs_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.stream_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.StreamBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "StreamBlurbs" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.StreamBlurbsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", + "shortName": "stream_blurbs" + }, + "description": "Sample for StreamBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_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": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.stream_blurbs", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.StreamBlurbs", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "StreamBlurbs" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.StreamBlurbsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", + "shortName": "stream_blurbs" + }, + "description": "Sample for StreamBlurbs", + "file": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_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": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.update_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.UpdateBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "UpdateBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.UpdateBlurbRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Blurb", + "shortName": "update_blurb" + }, + "description": "Sample for UpdateBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_update_blurb_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_update_blurb_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.update_blurb", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.UpdateBlurb", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "UpdateBlurb" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.UpdateBlurbRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Blurb", + "shortName": "update_blurb" + }, + "description": "Sample for UpdateBlurb", + "file": "localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.showcase_v1beta1.MessagingAsyncClient", + "shortName": "MessagingAsyncClient" + }, + "fullName": "google.showcase_v1beta1.MessagingAsyncClient.update_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.UpdateRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "UpdateRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.UpdateRoomRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Room", + "shortName": "update_room" + }, + "description": "Sample for UpdateRoom", + "file": "localhost:7469_v1beta1_generated_messaging_update_room_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateRoom_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_update_room_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.showcase_v1beta1.MessagingClient", + "shortName": "MessagingClient" + }, + "fullName": "google.showcase_v1beta1.MessagingClient.update_room", + "method": { + "fullName": "google.showcase.v1beta1.Messaging.UpdateRoom", + "service": { + "fullName": "google.showcase.v1beta1.Messaging", + "shortName": "Messaging" + }, + "shortName": "UpdateRoom" + }, + "parameters": [ + { + "name": "request", + "type": "google.showcase_v1beta1.types.UpdateRoomRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.showcase_v1beta1.types.Room", + "shortName": "update_room" + }, + "description": "Sample for UpdateRoom", + "file": "localhost:7469_v1beta1_generated_messaging_update_room_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateRoom_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "localhost:7469_v1beta1_generated_messaging_update_room_sync.py" + } + ] +} diff --git a/packages/gapic-generator/generated_showcase/setup.py b/packages/gapic-generator/generated_showcase/setup.py new file mode 100644 index 000000000000..b4f6da996141 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/setup.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-showcase' + + +description = "Google Showcase API client library" + +version = None + +with open(os.path.join(package_root, 'google/showcase/gapic_version.py')) as fp: + version_candidates = re.findall( + r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", + 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] >= 2.25.0, <3.0.0", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "grpcio >= 1.59.0, < 2.0.0", + "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", + "proto-plus >= 1.26.1, <2.0.0", + "protobuf >= 6.33.5, < 8.0.0", + "grpc-google-iam-v1 >= 0.14.2, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-showcase" + +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.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.10", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/gapic-generator/generated_showcase/showcase.desc b/packages/gapic-generator/generated_showcase/showcase.desc new file mode 100644 index 0000000000000000000000000000000000000000..319278acc51d374c112fa9cd0a2321ee18f4fce8 GIT binary patch literal 260515 zcmd?S4U}D1b?2#f-+QIfEq#=pWLqxV_)@m9Bugb*HW=g>rzDl-GWzPO62ve@dR6sQ zD!Wv#Qm@Lg!0vQHpaZP5Cp2K1Bsk-c@R4pphmZ+P7D>bOB1{6^W_zbJa{p!-NT#4?zFzRJlE>%sASchefzf$6?KMGVT_k!UZpXT zUVCDE+xx^;T7)oCq0)S5osdU&BZ-1vQ%mhdK&b58FqW4ajkG$`TCz4b+_P>>1wC6>UfNMrRXwB7*q+uF z+MT5xweZkNjU8#vG%YW+cGSc3P;OkF))$&fQ|ET{gcn|H+@AJKEq9jM=Xdn-qHq5- zWn>((H-h_Qb7`ryI8X1PIzZJX+tU|!tXF$u_PcRix(WO&wC6jm)An+sz1$cd9^?Zs zx~(}qJ-YQ)nhWZCLr0W@wfEv6b-MR`=!S^6_1A^_h zp7G5&$L^T@KKMYod8&QBH0pyJY`~(Pla-eb2illv&o$>~hT4lW`(|46MqB&*6_nL6 zs%y^Ax0jk4SLcq>@4u~7o=j>-hEI;(`x~8feWSj4-M5lT`a89>vawO!ysokTU)Qoj z?S+ervoq(Gvi&#jzco8zw45D1dMHh^qq9>jFgl$r&ri1&v!!#bY|85rJv`M~SjuMSGjOml zH`|<_YGoH@m(E!)p^c$5yDzlRo?L2Dxk>efi&^_@xmwm-0$BZ>gJ2Hq+jrr@1(uxv zHMGt7Fgp8=jvg90K0dM+VEN$GJS(x2Ew+Aqd3KROPF~EK3xG1!oCLtR=7p@im^Eh> zTfAFp3)BmX5YPO~o~+Y8yL6$s*h;hM+0N49?Bw!N7nTD28KW&%08h>NY;bry8yz3a z4i1lxj_*mcmyJ%`bK=xQ_OjuzvEkzrqa)+liLva^iQ|VyCq_>kr*wBVeEh!bC8Ng= z@5x%=h`E3XK-(RGI4k_Mra{(tODN7~Cp*hql{*WqsoAr$Qw(Z;X1O`j%4XURLBEV8 zTWBqwpY3Q4I{-JGW^=RWX9F>n<~^U0v^T9JjcWh8ZTi*Qs5aJJn{G&x-fR7*KiszN z$LwKWqpF|&aQnJJdzdz=`soiZTesUD(vp7q!^_v*Xb&rms($*zE5hg3H>&#i$x52k z)-`HZuiI4__`OPYxOH}RzSXe--!n0B5=xmrJ3F(yXbZz|0rFW4nfNFqF_euisgekb zu`}?_5|ou@uZaBe{#UHQpYLZ5AgzGZi^8FBd>-1-Z%C7F#!eo}&bOA%wLvJf)1Gf> zrp~t)TbaQ&HZne8uz01;P|9DmwvGW`-McY;vXa(n>ymYiYL+}_;LVk6I6~*2cMr|B z6o6w>W+AoEfWrM_+P9mC1CUl~hPN>^W#zB#eM@or~w)4=PJ>}BU# z^8m6WxR(}}TYIuoV@EUbOa8am1Vu0zItSdzR%W{$HAeUP#yDN@k~EuYb|3-fpu=3S ziaV{D^R4+MW``Y!H!Nb7jqRgaLcWjg$u6*@U|l!tzk4wD!$N4CUCLVX+I(4DX*R(u zPq)rCm*9yP&!#H@%h6e> z3oShXWfdW5{qtf81n%6mJN@uDlwWD|d^lP6R8krEm*d%W*^DS|Vvzv>FJlMZm5&5# zGdtUAE-f=y@rFpVldYu-E#{!<-#AT*8wA2lS5j_ketMxjJHOPiHPjTD!0B2KwdUIJ z6GO@5^6cC+Ery9GtvgnPNVT)Pu+Uyy>SU8`Cfb0dk};tyE)Uv2)||hXbuM<6TIV}^ zn7^sHWsNU;h3{0U$h&j@PI3MYtbYdfxI8(;rc&M{i~VvJ4EGg>=Gx2C*+?8j@%5Bm z#2r~}DjYqSvssR&82N3VQ;nx)!y2I zd7Njf(ze5vX+-Bcs@NtgJ+-Coi=OI>7fY*tkKxQ%W^7C1T_C$o+xYild#+>9&|o0@ zDEH+(gE;U=$44pPOXXgs>zW%s$l0cB)dC)?LC>3;9DF z(%5zmqqf(4dIDU5K;nF^NgLu3MjY0j;qT!l=xH4QmHG>Ncy`PvOAO)F{vyj*blH*C zlD}!~EPjqTHSPjyut4_wouSUI;^Qo9FWAD_xnhcUWp|cq2?jKz1KHrdhi=*T>Unml zJHtpi`*uG%7=g*MN0Ed5?@|8|{t2~9pa%GgZX{YVGBr-`x7?BK+Xp|4R2&Hh#OrTG zvtekf8e3{Typ%Vl31g|Wmlu(~HCL?UygAJ$%ceCidDzIl5M9{woW6t90~Jle{4Z#F ztkxs;KF#*(?-Bby4Cu(nL?(RYn7U>Et+ze@1!uDC5ndK^rV)eM71aiJouT<*_JeK; zUr9+9&dsvc#A~E?Ot#TpB;1Rlx~LQ4Uq=5#KJ-;S3FijW2LDP%l+BvTL7SjtzU`G_ z$HqO<>~6Ny*8iAfYE+t|^VQ+k>DlQY5~YR)v+?E0V}aM_>ygFkblh2+m0ptMGvtA#7u*I3KQwDv=$+aAJG2&7t&T!y>cl^Y0v1`*0ekg0_t~ioA_dl-;$(?80?K9aUT6D#_Dv-3C@=pwu&9+``EtM8o{bfH}ns`&6!%UP;$Z(=gNXaBh0(Z9C#Wmt@{&A zYTWr<^m2V&5`$64TD&IT&!?l(OYf=Hfz)D5Atw6-3C$V^E2B(R+5)Ggl%Ge3(AKJ@ zjM1`_*%ziV1I5$G0w;$j4&AesG?2YI8dz%md#WXhOWMyVf;Fku5*{)%4E*>wJm*@|){Ej(| z{X?#}-QUMr3*bK8@`|EG5IcgzyFZ8=Y|THwa`^`!<`N07*mW^i&0|m3N*58YLAY2- zFs@5dm1d54S0?SHHcGqpUSkjW)`M9^S}oSKu$!+<*qB1-$th23M0Nq&)*iI2gr7lk zGArjI;x~$OTv!XTfMIi$rHwY6m;t|J=+XK_{yxuEvuwr!xR8y`G+B2Qh3$w<(j|`R z_WX^}v*7BYZ-izMS&}sj_1JVMHnXPoPE5W)T0%)&-)5IX!F1&KwuiL^kzSTh$!n+( zhI2>3nZh%ayOPcX6bxk}|D&k^g{~TS0^v8;Lp~a*Za|(vjTc$%mosoKL&d0{0R|tWC$u3JERX zeF&dXRBu8{{!O9!xX1_oVE;M$TcxrUzTXa3nb4F3C~407QHstM4zs62sCe(-?m<&a za#IROprsZ4f`xoT@;+CfFV6KP48(kM>-P^^8|x-?-3?!u=kgpIbPm?qliLN|TC=RZ z=sH&8$);T1(WKkChzR~Luk<$&pWca)aWETqS5_x`g`Dn_+5K4%Xz~|##yXOqi!ZWA zSJcelhs**(_26#%=jiCf$k^~v9=x=3BfZo7=Gu_*eEnm+CDItMIi2A_!CgL~&oo8{aHp4!}l8muIF88qfv7LG@vRhIS!k8R3; zkluVs4Ht;ZCIObwRCI{pc4`TURnlHJrh;K6J2Pkq8AQrkWQ(>ENEke0sx+=PGvMSi zU}%$z8TT>!BWNr6dV-H=iolKeC2TTSUYz5Vh8BqJ%q#Yu9{R^O?|o5o@2iIQzWjcC zP1^aoM{5f}US%T07OlB#x*beB7zh#3q(QoCcnAX@rly>7gu@Hj@dcH}haIaUCQ8S+$&+zQ+vYTTmJOtk7=!%dRO0 z3v|h+GP-uYwO!;%}gb`5EF5 z{(kDV2FZS3|}esZI6Y;Neqhvb0;l3KoP&8#c1Efk$T#cm&t~iPw?yjKKu!gWSki3uzu@o$nS~ z%$%9uat;s%%@~j8t_JN0B?J|Q?A&s<0#z0;BsR7PceM>AZUf!z#946LXV|0+L{07r zOQEKDjdWrX33TXd}mx{PKmZPYB7Oec#m7{dK*bhb(g+6(vg(A)#ji#YVq zEkno5M5n#0@Z-3AsE>jZy340pR=oGUy6h8@R|=VPTpj>fLBVZ@M;3o&@RkCIG&43Y zzzOZd5m7QDuNiJ4(ZHmkmAEou74WK!M^PvyUWITnQPnF9y|?Cbh$2X}r`u!fqp9}X z-pOS}opkn1x2HP$ys7IR=(Oi|X~JH1PVuEiyI_rBQi#_srrV=zZXMb`v_BgcQ)y-6=Is>a=p>wx-nE>Z(}XBoRo2 zG(CPgw}zKwj=9+f5pC~MJj--;<~kE?@2455*;AM#7M&-i$!1oc8F<35W^8D zb$SIh4VN9h3CjhY9%Ol7qXs$_eX+r$5Dgh|4yYV)&6<~3ze0(JF9hVLAi8@3F4}$( zf&d-e4BW!6&9dZXDS;uqX5OM$=LyAz*4koBFeGC{&BaBO7uji}f^I)cab0E$*X9IW zxb5~*HGMyfRudoYP=mzMN@VPYIL{u*T)eWNFSOnhROEzqc#j1+iFH8S}f#18X(ev+; z|oWLH4;?5m#HNu%}$0%dktwe17c)7nRb|4>n-kr2FlvEAh zk%C|;G~{4Z0fVL^7*)XdRMNL4jJj$aH@2k*4UAf&_UWW{`M_=6U>qJfIx;a*nggQ; z>n{f+@32OPG!i=`f|_Dqr0E(Rep)m=Y#mbfPm-6_0$+qq3+Y}C8NqQQ!&m^_y4!l0G4JOcUToO?j6P=ai{H`cb-~Fk| zrpCTvq0%l`i_*`8wn89Cp;zBCGR(OW8kS8EZo{61t)EXqC|}@1%kzcFN?_#d$hR}3 z?diQ!&BbY3(m{Ge_V;Z*3iJ*lA{%EDOaoNJp*nq8Yckt;&&08#yTUe6ERP;X&1C^` zJ>c;($>mqaB6$2va&4CWZ;r?HjoRmuq%rV8$D?`r1M7%v-|gTR&b8S^kYkoDrY{H$ zfFfks@(%TpAaD~HhUAab*j3qPolUi?RhO^A1|7JZOEE~tfxVTx$XgDkH)~xoiFRS* zB^SG3F;JlB?6}Tw7^u0g#D`^@GaGZzXE_^XwU*iod*>9OANgoLxVX7{996*TdT19k zM*hDZoPRFauqnO;=buaZx2FHXao*dg{dtmHJ@AGkJ7LkY%{eEEZtRCW`5B_$IHjHF z^Fh0slA9lMR;#MD~KnKToc_D*dp_0UH{%uO`Xffq%(~pZuhv6F@w!XcVIH#El#s*`0BD z4UvEZuEJK#?zgtT+UJ7i&ePmO$i$rCGp!uCS)ItwCpwf&)1F76mz5X`sgu%ltF<7V z%VmZQFlnIAi!9r(CY%KdZyEVllkGRgA|wB5vU^W@gtIJ3qvz|1&L$4LsMxyWaw)UE zJZ>PcM_Z=IW|IIRxk`K4*OT5W)BW(&L}Jxnix*sPEVUp;np~p+!O1sF7$5nBQKZGc zj+9Rku>V?=|9tC!m)}$eHx^34N&zQy6oB+TwBhqz>_Z#=H;X>B;eV4pCVPUG{70{^ zVpa1)#`XyPci(iYGqpIoz)9Y4-grw0SdTRZkEL7hMioAsR~+X=?+eqKtViJh^7YY# z8$TNA{^FzzHDmV0;OA@Uwl&`BXsa+AkGtwOr-3;lJN005rWH=S#$w|+X*!Ksfl(Z- zgoDLZj_{VAG;T__E-X)S2$N&ad9{>k^|5|`aX5e8xG~*wq1Ak_Tvdm8>tmbsxK!~_ zx-syE(^{RJUDomIY}M!sT=~fR!dDY~)EG`TwC0!3dkb}IVKx3nsIjt@UVRptSRZym zPD2ZX8&`oa?$*(jZN%>yhk)W?c1>xc9D!CNH>_&pZh7EVHc@=nctN_}gLOLL@b%Se zG%?q5X5JZ#l^dgJzYCM6bt>+(q}v@E?DY1vs~Q+LDfbZdMyWQo**}bBj)nKQ^0C8@ zYKPL`hkDX2D@x z`z5I#OSk0oa2lTxl`rZ4&d0ft|t89?hUBG zS~1qE2cipQ(6D8K=o7ZKysRV?2q-!qeA?8CkfCB@c=%GO8jWkyK3`R&h-f`*+_OIB z3vEwHB5bTZpT*I?j76gkNtz@ z+~98^(hC`lEotAxeJ4jwA3kyF;L(x(N@H`H+Jn1~o*16!PxA8U@rf7Q)?dv(IOPv& z?e=ipQj=XgbnNLi0d1NqHv!VStZL{P zGvn7((jAvV&YGw$SfZx0V2O7WYu+*V+%-{PlduwvgYT-Omyffp;r?EMqcvf8aoXeN zo*-7O-n)*O=Xgb1W8tgvZtt+J-t7Z4s~~-Sl3uoE<7)zXO`6WmV+MBFO9#o*6vNc*H~h0Yt#O*cN!e5iRkDpj7lsZY;N zx}HTR+pP*?Bof==ZEXY7HnCx>p?4?r>X0IF^``OsbenwAGs5fHOhUcg6 zp;F^Odbza%4ng2)QV>i%czSv1>2cxW>K+?iJuX~a`PuF1 z_Jwl`tH0Y_{;olll^@<ysTjq7l}+1YWeRjw&_ z%h=|rsS!IdK5XwudA7AZ`M{J@-k{A*cQDodOT^58@p&*{>TLremYQl zYsU><)t^fSvd3BxoeQ&Pmtu=ITD3lV7Fyex_6rlX6k@fVR&6uS%l#s_siszice=}} zZRBCm<8A5Xsswv%>M%*E_8zM(w8Jv&W$_hoE-p`A%n56+!>MPHw4OELeDFZJu}t@k z4XIN;0ts@~p%aHkPLGeid<0np(M&;@r^il_fa=&tf3+mo-&^Z_UjL1f8a8)pYKag6X(m0x4JKu&S!Z>gnpk+pb*6HRH zYpcV`7GKX>xq7}m9x4~x&v2;P=q6t={QSc*`669oyoY|57CnPp?^rJnMpXXqq9%dO zT7RAY*ZX_;e^38<{@>fbf&XvlPY2&rOE;Q|qlv?RFNJ7I+J|9u^Zx5rZBymiLx;4v z9q4g!dCb3*sfDHVAgkK&ITlKdBWceA9cx>=(dPZD)xfT{?;W?sH{3gZ`uK^lW5Y+s z!sm@E)7o6~RTsOrL3;$d*s`oJAUpeU+G=en&&}rI?NOR|rqf7|GVyh9R`%%Go5aC= zY2EPKNYjAf{&kJsw07vk*kP6wYsm3_`sC=yAy(Dk^V1$jnwDFRHa_xVP-<*3>g}mx z2S>*GlkTMlu?%)t$1<}-nt0YYMycz;->am3CCOZhD={SP3#Wi~jZt9YPSIqGx zq5JW4EB@W{3j`Qq=09!Tq8)?AWLBFcyLuQJExtP{f8~K~93eS&5_jkEL-(CNb^ImA zPrU5-SbwQ`tM)7|`;%$^N}w87q-%l2%HEc4Ievm&m92H;?z=}0O^mzcBp(EplkzHi zdo|s*hOrH{?_L#GyZ5f*`fGeMB&p*h7RoXERMHe!!bN&^7LCBQcvpnB6wgg-Z0t!J zgwt4NCye^hd?m%GhTA2)8J%CsYtOexYsQhlQf-;rs$>1}OO*PYkRmVJF-mTJ6Fw3_a{R~ zL;bP*%Yjc-(%$%(?b&m~s=4~Xq`%_%Vf7qoR9SxW=PGMnLs%hRnDYue>v)FVu`S{G zq3~GVG(x6l713DKwZy$+{qaR!`9OMQY**o6sASW{M{<&E7`q}=AjZqy$8QHeT}ii^ zLLucL_wgJ{(;`YdpldZLuljCiI8UZFR%&42e3}+-E{QhwDR(uQK5P3Fs=q&yMkoW$ zWNT)2K3JZ;!0v5^d?CjT`3L_oDqoSGH`>$=_7}qENy~b1Pvzx%gYUJJt2fr)CjpC4 zl*&;*ZrLpPF{1LZ{LjW{4=XGat;fViD@W%|AOg)!6b==>B(D25ft zGD{X9Dp>T@TB&gmez@8AO&{P%;;L-s+ zCH*C)M*m{GAdZ3rmL#jSpgH1J{jifC%+$#NMGldWS78c@P$;rx5bo;9oh`Cg@fb@n zDaLMMS<8TViqM$$j7TJln!z=qgLP_^SUqB(lxx_qV$l>R{EBlYcpzko)%lIQM}q#k z!O@ARx#sM7r2*ybEMvuugICLy7CTS+B;|GRAF<}NIar1VlE5s$v zPwxZ&ex49YL0HG0Q=r-=h_RKD9W%H2ppJ)(#2USrs{)Li7&D`-d5abEcZPR6> zE2U^v)@GP|Dbuk6ez7f?~MHu|0YW#rtqJabk~kyZSrje?B%ccIY0GLk}MuMNhxaK)HK# z;60pL+0hcK@l8s!)G zKy(A5`}TxJ$8mp9iJ@Cj*lEUI(h_wc0}-;P%|$Z9Us}ngpC5*5w$6Ddf70YLMU`BiUcmENWV*@3zC`7 zY?K_~hhIt~K<%}mfbr2lE<74Pb?Bae^PzPAe@?RDW%%vlf$Tv9i1z%Ch8>I@FWdPN zdz8HtvrKar%5R?m;6*G5c}Kg4D3uPsm7c04-hYQL}_I&G&vD+ zFXzXI3vbTD&f$~BX*#wD;Tgd;6!Mj_o@It+oy!_Tw3*n7hkcnn1b(k{jxaJ0d$QWJ zWoM>!B&GB?3sK)lI`f@5Nhaj0#g3_CzOb1l$Jxu_Q8p$r%lJM7q=dZDJ2{?9LEJm- zXmqTDh2M^M=rA>hf0WKx@o?lTCq??Mbvr`l@|)Hjj@i)l)6<#nS+^(VIM+{qxOd$x zF&nym`op1hx7))T8dd%Dhx^t&*B+7$T|fQd%|$MD{q%>ot-Ct?2@fqsYEsB=>lB!hOM5JUxSjHV7trCq)j#Rn94Q$I`j;aAnKGbD_QXU^cyM`F1AT z?Iq;*{1nFno~-?a>kd=~Ug^|vC&&aYy6h6^}7xOLH zC(lunO+#cAGpWCjK)^oY^emD3i;|r&4>=jjU(}Vc{6&4wiSJ0b{i18HizO0nzvy{4 zru!`4cJ0n}FRu(-2O&FY+Lp#;1yzH%Vl zZC&!}uH-p`*JMVrmcDV1WpNyuY%T&xYiSBl{mTk{+?DsCB;EkZ4 zxZh@dK;{RN=Mw*ToDtdX9;U+F3-zRE!1vm?p#2F|YpMOMjY1_(S0LwFFC_L{&h&U$`!Cfrz{ zc-tWk;9DdwvQZ9m%{q@$$FYX$ksM}DHB^sm%>v9EYN#H$?uPUQ1~V1!P4*11%^>X; z0pVrtY69ZQ>8jJ;y*ZBRr1-zLZy@x*sfOykSKSy(^mp&>n{3tTNJI4{$=>j)helqK zH$qH*^(A4|QISSoa;>jVN;LA4oA!i8);Fq0lcCVadKx*JH?p2aj`pF)+fpD#y?S(T zS1i%U(LH-ZBU~#sV^{KV(qe zbD-E|S9bFKH?RpsVM0eb2re1A(>$xBYm2S((q3%c$^L@|g$amm;pULI%>%>P`GcM)lLYjobF&daDd;+tqbmhn zr}`pCNkP}Cf!$#SQqXm3?@)Tbku3Lz+{XJ+pIHXaug^49g)&#EhGHBU-f0 zyb*QR49kI$i9o9;-jN_+H9XrHNFGq_RO z=-jgMm@)mE)Ajz6E@x^Ri!u{2vx&&8_@2gQw(Tg&bUbs_)p_H*K3BVn#z!7r-MFUb zT&ZzwtLI9MYl_ZoyF71PlXQ-m-V`8bnjWa_%U^4v9w;@Zsd`}3VDX;j9=L9IQKq>E zSV@j)`ku?@TpWEapDuCqxv(6QL>zr?z*!(A8kx)IoQm_wzA)$F=<|6a;^^}^;fSNp zXOT|D(dTnW;OGlUBnNTyg}f1Q^o1M}arA`&=kH0fo<lQ%1@15>VynZubCaBxEPa!2P=zvunK3W4l@!jU6xQb zjHs}b8V;3U!G7#UNhju-3xUl5D+5_huLx9w)YhmzbP1AlaqppgnqA;~D5n}1`5wwi zk}`OCC@0B^mh6Q~kR&fb_k~j9BFPJ-#s%qxoFu7F;}>$~!!~*`(W=uy8EvB%^O@5& zda=*BCGTkF;*~BHP@<8GNCiJ-GncTBK9bxpuv|=x?@khmWe>FM{o2mD=O<3jT2mqQ zZ-$jU?-nS198W9dG|?s>QJfLmz8}ef-vAaK$=R>A??-TV`Y^S9KQeedt4Lg@{uAq7 zSE(3t7hC&@-fPkmkYiOxjefF{92gjO-A1YiCpEEdNlJBBzH}6&U{K0Zw9xjyI+8-%wfKmyW|DU9+qGY=!g5hq9Y><}{yejLR9BU$7%09h}gOReF7) zHOm22y+ih5a&++n-za;AWR)#&eQT6nXmv~RfN}k71?S%8&@C1IS*3=vFMPqe(Syy! z1HSlY6^>C~2wzbCIldT}QA(Ta<+C#{hezQZMS>%{6KD9`p%&Q|%!*7Lx7>^ZMUoaO zoWdaLamp56O-dbjP5h`N@F;@^dP6Z77=n5(K;ys~4*)F=2I6@WILu)eZ{6( zNyCqWfi~arLmSMk`=9w>L>}~942H9VJSYtY;(u$Uc3D0c9lPd1fAN4X-df?{bsRn` z>+$jzI$+F$;)@=>c)a`tXN=zlC(WDG@mL;gDjx8~+bSFrjD2uI_Ft4ytaG3|C{WzX z7ym*i{%j=>3}->#Al%!G1^AFCqFU$uHUZPD{tp-_4=LXR5j>^_;>E3{av{8GaQo9^0#?jXN%+k5F z@sJ}PT|)JXxl3vAiOROi((6KleT~|aLhCk`+y(9H?A1C;M=H}|%^>@$RsmNZ%{(c% z;)HH&)PA{4G#mMX2gQVLqQ6ml7vmVbLJX$U z#g{O&l~6($gK8E7Bx;Zc3@|pewNZQbGiqupO;NLGYAa2>+i@kP&((InR!QEUGkr1F zU#qO&h+Rv=MC57I{uRR<7`P&e!m)m%g7gvI($;TO(EdUZ z=KLEKBrtD@mmjDkp8J5)&a^}^wxnalAE<;36TG#`TdxQ$=~(dxP+CJvK=_*lOz0LW z#+HhCX2T}wk!k08WioY#+<7X?%)gxwP!Li~lj2e6?l1( zq5XCx3hiu7*>XHjhRoK;A(Gq`tsRpAfH=oo#JX~?{BA+y+Qxsk zLVS)-5rQ?v=UkiqV?#Q1KUPVu9au1&=epR_;F*0&t^up=GL_}}_k=s-HYm~rni5A~ z3NoQG8b*4}DF*FW07Tf8$K_)M>=GzGR^cF^!>&9oAFEvRob>0MVj!Bc`a( z)lWEo=t+3>hI#Dh20t>vabcu#r7_3ycX6*JQ|O&Z?p)E(p}f9>m6;{kB-HH1TGO}%GSu1u~bmRYw;}~0>a-PYY2Z{@swo+htR5*W!AH$7*Ye*l;gz2 zH91+Mhb(4Hw$xbYFievTiWdey@PTH8C*=o0f|SJ*+Zgl% z;C|ptYl2D6p#fY2P*Vt}D5ycyCcYomOeb^c9BP7+WMn_rBFG3z(wcIYeerSbESAr^ z14GjOVJl~+-6I-6iiirRBOjW4wBQ9bAn(F^*oB!Pb{c>p;rPR>(zu=rPXu4gDVZS~ z9hq;%!DhnoGUH#QC0?tsh*G<`8gw+z669nV5eLy%=E6v20Wj7V_d}Zxc;L!ei$)yF zdWLcY>{ zhQ*~ik`!!_vX&L{q@bySp0!heELgi{-poO6_*8OU5eM4b{PbQTvOKSq}05zr5q6co&nry+-X0;{wa-xOY#w0Xg36tceY>tA&NF&TdoKGe%(xX$T z2;-#OP5W~O;H@k2!A2rB>}zDMIg@9-)P!(R$(+JOfIdtkG#r7B@BJN|GG&Rax4^ zZ0pido{IVaCAy~QT~nm%ry|>?$fr+59fcxYKNWS9x|D^#ifo$_Em4du;iRG%*fwvi za$wsOY3Z-Tw&iB)Y4rScW!?WwR;Vk>gYfx_d{rZn1o77uLM=3s9*yL0;z%gbKSl4K zA|v^mI1-9{`ZsYT6zTtO;z)Wll5bXUnrJ#G(Gtbjl1B2)O5b(ytyR8$S1i)fH!CeY=7K`PU_2_TcU6c}=B7aH%KQ1oWN2SHXKR^HA4|}tURgMcOz$=bUGH4OW8@j-l?HYV zrx3%Gq~=5je>bm?Ln@_}?jod8S|5uULVM(brWh0zia`2U0XBU&#j*5e6rbHWZKTA~>2n>Px3u(la<#KKinR22LhRi2V5hgy^Yh8NUjjRqcVS0!Ks0+mh?Ie!PkI$M zQ>*m~A-@n2LW#~Pdgl}w#xF#KP~_8JhzOxb=f4mU(ksY*F~M)CVNjwaim@fJ@n1~( zviR02KiAU~Qkj;1F~N7~FoBRK5`5R*k`O{Mwj_i+k>I@!Z)xd?1ow3)($W(N{_C4T z$c9GGFDL8%H3%8(LI_6|&b0}sk@(V$9O*Z|oZxO0ARC07cSht;0uYK02t|u8^TNRGK#S! z@v>h_aC`fw;$^>=Np2swJ>xi`AIoFII~&uYW4j?=Na-dv z*Xkl}xTwK95tE{wyvShQ7xN}>FedfBq(6cnCiT7q5W=^ZBHowW@Pb&xxbnW_=H~|h zY3coI0cfmJ-s}|shUa1OasXvMqn!w#%xCW}0F>DI{sKUm&)#1ESO>uO7Xa1)@cjbt z*Eh3j(nimpBUSKhWtyE--KR2>4! zmi!D{d1a*81G?ZG+hRLrgD=7v!Yu?id`0wZLQ!?)CWbkky+W+vX;*x1Z_o; z48fX(%UWhTX=`#Cqgx<0ae2k;0(Y%QIW#p@=At+utfV{wKn<-O0f5?Hm{=nQb_djy z+EQQx>%UYt#%Nqb`C&N0ir|6RGQ}#k(DbZsEe+hr3QlN*^rIN8=fVaeCtQd-3!2y@ zr2tz11=Y?Y+!Z>VN8>~w3kx>x{5kadu0(ag+Tuo!pcESavH27PChy9qh2LRnk=t_3 zG!R=aP(YGuL9F{}^#gI$RZM1cq3yGv_qrx7gb#J3nqx)hUWH}yV>5ullz|mvDFnML zw3%A#)aJ0G?9aN2L09FPcFUJoJkVGfU%7Qz{|)V$>XF!M9z$TX(jD)iIb*J-l>8cm zik@_+Ul(xhHsgourUKmV{g8z)hSHdyA<8l`aOidw#B#E=`bjd~ig^=GxSK2XJVTW15Ox0>ipjmxEW{M@}QIV#q}F zCrR%%k3CN%HGU>Zt{eC-x@LsEM1#GTDTm2evSx8Bu+JQDt!}5ZKbazLfCsB!@EpLN zxM#uwm=4 zn-|r|ViMplV0Xu&?V5j(SX}^N)W{TKjEWnPL&xJp5;{ymC*v} zN1RrEz!JoO?&pqVNZGlIP02I`-K=;)7Ec-Pu|pT9I`Ty(N6y*Vd6-zx=er?+A}vE% zTymZTPPQ1#IN}6;8!meVy=WkQCN9!QpbXY^so9)vJ=HNC>w-)BI_w$|Wvl=YXN?89 zACxm+;5^Qk?81m2+$YAr zqok>?bg<%k(OsGBu)4S7^%9q+J3p!s)|pf?CMr&{RI)EcB_TCq!k3bMHzrVIlE0KZ z&kYe2Q4+qC>^cyeLP_{ia@&j2T}A=a{fi_S;dI7?M6|#dG z{-OXv+T33x{d;3&Yxw5#iMxpkEBOMNQyn?l7|0=q5Vg) zBl$9kj4zxm7I`VJr2AO?$Sf?yX0F5Y2&Y9Ze=}LXEj^4Cn#Q#me=DhN9=t7YoUg)Z zQu|zDv!s7!2QA97GDNA`!`rMC21qj-%u;L*;DFysHg4i#4ey5v-(j^4^!S0#!F?7= zT;v%!;TKxvA)tXT`34iCqSdlEFD-e%qCKFi@8~j&*cIi!#LZiURO;92mUxIB&H*ZgDuNTtf1v7NWI{t zPcJXAIdxrSQ*JawWt3B07_#zICnk^Xl|r8BEOuEIiIBOg6hN2G5vy=k;+Q2)VcF@b z(NbiYrXhZXR0SJBe_2CT2+go(&HJ^bt6EtJOGzT|G%u2O^Zg;Nj6~rE{ z4e^kv&W2J9c0P(s-|MQ^J~#an2n9-DzTQ%0zyEi&Y}~H`w^^8-iZXOZ8)`8#$UrUa z;&Zs^mzy)KyRvN17WXUx4`KI4rjimO4|TZmiuf&9CGr*P5y4xR+h*JYh@Ti!g=`i~ z1)?|~6+NMlfLd%5(v`X;4*9vd!N_(>uNHoq#l1hSu_>c~ucz{$E=W+<)R|KBAnK<~ zH&OfuP)MyQ0>E{|sb#nFhLC5AQVDq!$u9`iIw>E~_L z-4SF`Ur~Jif%I!~Q=|!T`|qeG`v*Rcn?foWqMZcF5+UA2z8AB>XtRL=v^t2jMRSst zx&$d9q}zwuyIW+GQvFE9C7UgBI@B!5>LS%?EGSOukN8(k5@EOtOge7aP!no6)H;1f ztgi2gHso|sjDZGb!ct6y4LiB@6xWivQXkrMT|ni0vPPX3!RI>)eCm|KJF5L2i3*0m z=R2y`ct8k6@cE8vc1vsue7>W4)6Jv;5jr`)@MINd#E)m5t=Y9&na<>VveeB6n~>3_mauFp=-tdb zsi*_vU}h+r0naocDZ8al%6d{hAO$xVB7C0{D#Vm&3PCpTs(iSc7%o7?;cjBM?a=eV10?sLd7UK;By=@5LS2ainhxw6?ifh2%S8x6G!C>tSQh!PpEK zv=zbF3>fb%z|aAc_f{M3HcOMufbrfcDK9LvIZZfS^8TuaHW${OY+Px$m-AywR#UInUiF4NK^>%sb!2}p7Wm z)X_kvvVLF(fV>FozgfVp^FF^>&;s|nP=ppf;%khe?beggO|e%pBmSF7^74{x$F@98 zcd(Dd)=dh<&x4k8A6~R@Bv<60Z(QnFTB)1liO%30`vJL1G2H4D0?N)=RIOPw_C0o5 zNR78bUE&9{dpl!>k#;g&ZVNh69p~aud z?TbHvf0!M~l%^!dFV*G2;Nr6F4fLapIG%iO^N5qB3+4mHIBQFvTFjA#+fp_{oy(Cv zFS;@Dyz7{da|9?G1_5d3MHc<%qm0d4*1_ki{T}K@5eD)3Dxq$Y4k#jHf4&-QqZE;` zKVQW*`sd>OeKOE}v6|dH@PAga!|o??4I+pn?oc)GuqoLEAK73L`>=Bt@iXD(ju^iQ z9+l{J{w&(L)|VZR^xyy{MFY*_G|b=v;zYU}h%+bZdF4yUlcxni$WU_&R*w!T(C@&n zA{z$Qg0PsdT97f)$;AW}QbZL%a;PrgLLMnbn-{_37YjVfF8al4|GromJbtmd-&1pd zDDe2j>TM(OEqMH5^{&I|R~(P9slTiyw+#GWg<2a(1#*tc=?_`66)r<3-={hov{})e zqyOpD*%H}1S;_CifFmkp$^FX$l_IOZj2dm9`F;Mf%Gt{BEvWp<>a{n=BB=b!>h68c z)Y%)JswUfPZ|KwB@Km*Lqt~>(pXmxq(b*)6U2?NMt zC!eYo#rXD@dTfnA2tQLJd)d$RNRR{TzOBdk^_Ac4%`YT+E~R0q6B=S3!l;YOoQS2Y?p&M5Cu5{+F%jLyUi7_T{7%^dixon^ zs!7z?Zsysxb?Aw?2{xf%V2b8s?OW$0F=&l3Mltu8j}8f62roI-IIh-FL!D(T(zyf1 z0;f1zXUR7#ZiYrJx2nAT*z(o3PoqevKu093oH~wkYsP_?K{6OSR2BQS6ds`;=&G)y-(6Gvk}`OAO!G=y^+R-M51nE)(BdYQ5XjUzV$Fqr~vH*HEh8oY*q4ORplW ziT>QjCfdi0=-YT$zVIwohzOVX${0YabN}q0@>bb`l4Msb9AwFPnQ`-Yq6_V19mCEw zvgr7UhxOz}B2F?&9zm{U{YfNK0BpW|-6Nu|+Sn6ALSI26OK?kJb=+*W$RXAXts9X& zjl**kQ3s!pOn`}%$+o&oh#0}Ko}A{nKIV3MD^F;JDWQ#O zQ2t+PA)Awx`GN=T7`6vi1IO@ZoQin=?pkuyz#ljjN!e#Y!gNW+g;j;9Alp;(y@Zox zcm%}VjeVL0)hpr+bPXw2rdE-bI~$}EaxSXL+-s+&v)H!o)AVgw=yTvBmt&m35cnl5bw}?a+jAJUIqhH zro-gsMRQ}Qi^9Qu=SZ_2fjDsMjea1bAU->g5xF&Q4fXwgijgA3_ihp2+off1)J%S` zmfSk<#=0$Uzj!WAOf*x4BhL52(Z@|3aSXAvJ-)&$wVkk(f!}i{ScAoiBor^)7Gi@J zdS7rG7j0-|Ew#w5Otc)h$M{dHngKAnlUFaejez9vFZi{xRnm)2_{Cv$j+OcDYdT68 z2=}-7b#7+F%vldT5ZF>0k4M`?oyV|_tfiQ9_><)QSxZJGT^DT#5;~{Y!VnJA#BGf~ zD;lgh$n6;zG!BLGoSkdK>#%uxKzY$EqQ|)TT`%fwe%D--Dzh*Mi@fa8<7l~P#hI=M zCkhFrcY_|mJ!lv;HmL}96mDI?5qK{Ox&lPQtfvNu-6SXi&l#w*YqTGtidhAa9}`T4 zVunGBodRUgKG|ijxy`8X!Ai%OuJ}bM>$q^ZYG(+8%DJIY(Shz|37k=zHN=@0;i@03 zg$M*F7sCEvjZDDKMiq?q!5W7>LlLg}!P+$*7Di>b>IZ8(ZwXwLR93%LOMW-!s#+w! zRa?Kwl4fo6R93&u&OTuIw`_xoNYXfR?&^80sOix+_9ZLow`)Y->@r?yd8|IHrmi%L zd}(T&=3*$1z7-hMEgBQ!{cyQ4${$&?u@IV=(7}}3- zjxidhKKdeJmVyex<&d*;7YWGFMUZ~30DfR=nAr@%?OvfJtbC77?PUBgKp8#lM?&_D7>#q0z`Dbe5|EMD85v zkY+=xzWNB8(Yp^@WB^l}&r*EQUU9Wzb{S0S(wZ1T>4~ zR6`P(j&??U-73P8sP_=n;ZfsZ)ygEIocB6X;l_JQHWKvY?xmTe^N&SCqxW2xeecA~qwI?lw(xaLY32n*@u2pCQLv!Wm(eZA$#XJ~zbdk+mAr zupqG|v%JVXi$-@sj5oqdmf$d&O4qs%F$=!nopk78O?-nK9Y}=fXv#Ti1ar$UFpHIW z60Cr6Nl7aL+)8s3xn(yP)^xc2Yqy_Z*d4%7s-KwMB_P;Ljk_&ic{iesZgU5QHL7*< zrpV8LPisWDifo%|l=kBaMqAkj&1@3Zb>D2y1UmNtSS^m9`yD@z86& zqPQCB@QIz1`}W^*%ZqM)!7aDkx(oM>2jqw$&rZ86#3!~|Tr**qE_%p%!p52xQS(1n z$m6nge6AKU8*Vh~$>(ZhHVoe)wtTL3?OZ0v-Cy@L|>>89`s8UqA_5! zmXXk|Z^l>2;E8Z~MhFe@K{58ub~A|41bQ&X_GJSzN!q&!M+xD6>>}rIlDSUC^oKRn zBx8fr>6ov-D3jl&M$g~X*1e|g zo_B@0{hdsHGLdeQMd`agM9kA5n5RX@JVh}7-H3UL^#0w5d5U2EyAkt>$NQ=JvtuIN zB+UO*J(x%-0S86LJVo&JQ}tjX-Q4JTZGGL_0=^WF_u4w=H_w2t&BE8~>m;Kc^Eic) zPR#aiqB#Gu*>Elw>%FAp!W>E@ELUPE7E60r6jW0e`@@bx4H;OpyTZT&CelbfXmK30cM{>Oq(nwI{ou}O`>kKVC6ph(3yu&0U1Er;Yj zBQ9y~{2WJe1~blxBU!;7D{v&u`muUolHdd!Jys7)k|Lbwv3g*V6yZIO)nStIKWt{v z{apQf_#ZZF-ThoWI5Q~GRk;WqSy78?vvlw`*ME5a2O4DDv>3;&Y&UPN2e!srfO&I0 z_#Y@T?l;$i|3Oivk3UO`YqJ*D<8g6O0uGA4xF~{#$K&GK(&%}6eci8y#iiiPx7T}j zq<`E6CRs<7b_SeI@>28~!u*$J>Im5yc>L2F}DXa-Ud=%+?c;pecf; zCn7;pWMZF)1Wgfwej*YyMF{!{5wvJA0iFXAfVD>1Xa14o{TieTk9{-AVolZ zGSc7{M)fPt5)Ez<4gN}`K}x_u(P@w(H25o#2KyU5@2;==H-QEfWc%(qp=kd}rCDfBCG5J^>CDfBCG5Jb&hgqmGx_t z{nih0mC+!e(qaTvtL(SpD&wv77giZXK>e+_%K91Ahn}TX)~{9ep}5K@0S852WfWOu zABwANYoq6P>g)bfSY?Xl{+)X7W$Ay^D%+}6_HnH;V%J7xI7U$lCcS5Mk$E4__8JRT z!vFs*G3FJzWn!IfDME}Nk4uaqRPgb*#3(|yACF6nB1`P!afwl6iG5s4?5h$Ew#qyH zhxOz?)T?FI9Ee7_E%y4s^}S|{-wDq#>ns+)dnP7M$~;AY5Z5F4&gN$w2K-veFfE>?njS~$;2 zw;VTyPXvC&h(XsM*4JNQu6T-CHJ_~4t~Ou2m8rl3zn;b(umV3>Cwb)cIHdG|3ZJUi zb_{Me`y~mHvH}*560llc&F|8(2ek94`sG)ow}*Bp|NDAv+u)6*??WCz>~a>8;k@v#Til-(93Mu2zj)Ai(!>Yg5eG6ckfNI+tIpRR`tm%OF5PuH*Z z_z8*-(5LGm9|T1R=#T0>engET1oTJst=Aim-YRMQPk)F!ng#)t79*&V#{V?(Xx;+q zpGIk%BB1_h#~+4{P_u2%-W z!)^4rRX6vYYsV(_y+@Es*E1_GXIk6Zbcd!vfqI7Nou&5i(3*wZVkYN+S zLnoIV{2T;;Dn(lQ3Byk2m&&^f!{IBMJ#Zj2v2&NR3(TT^F9X9US3A^RxH!??xoel} z!JZk!7RM>hLE&m5x`5H2@G~WHKgkSmo&~Q%5jyDe**ZD2|3Gmx4P}}BLOuC&7~a3} zNE$n06a4sH`SrpO5xgvgqC1;GS_r<95wg>o2}uRy_?d1m?TsmRxDp7#jc;c=r}HR$ zSuV|-K`dA4>vEHLkc#R%2@`;y`u)bD5?HHp>vYk80=n!$IqFeI>qiI<*z@Y_72$$( zi;1~^59P_`A~&VKiks2}j6M4C<%e~JyAGer zecQ~2PLa00T;J~Q1&Xxv;rCT$JBxNhXYl#6HcQG!lPH^2AlVD*Ekq*%hsVHHb(=CfP1g+wNz?~iE z$M`L$`4DGA+8+3uKkOWJ6s-E~Ec1j?LVr)s_?N1dg2@Oxx z8}4_YGA%t-Cl!geMCq^UA=`2zk#mP)Y)PT9e^n2We!Qinzp8J&E?{4wv42%3+p@RB zr(dgwZ1W8Z9Hkgrl56B^1x#{{e61eNs8X4hzE+R`b-!Lu{6KIck$-?uCM!VJ(Yn6aFua=Q77a-EniOVE>4k5e#ug}GTlx~+9_F289{!pyV(T_PHIXV zHzAesxgboR`C(?9MQ<%#;0~#uZ95m%X~VyhJ>aLdLR{Ol0^id^ZsxD`vq2thN8eZ^ zeeu?XS-jOE@a`6QQ(|=PG1l=KoS+?CkkcKRftC0#&u3z%r|`D5=V8a@^(-S4maI*L zh%7%L?M^&hA3{5$hezbJ*U1{?!F-sYRs7rSDek_C(YJZ1ZV*vBL|YQfrjP@_C*B-G z94wQInQ%JA=G%uHwv$*eem=0_Z|j6(xQTXrIj=n?W{d5T_< zM)cz0qP20`aR=XR*KX>SI(@+3EB%N5(SNUer4;_Ay~?u5Dfb8eQqf5J$t zQ#&vx(P1vkr=Qy3jPyJoDq&A(DE?FId+O#D%{{Zb_$MPM@#a0*e*T}`Z&fE4(ghA5 ztR5J!AE1?CgxwGLG zJc}H#3_coGiRg`75tuLnC>~tVolg3l+(#W!tZBp0G7CYvEWJh4t_*NyLi7=lU<7h% zKT-g9h|u-pW-kBG_}!?6Igwi!qoRD(j)^nKrVQ`FY$vfGo!Lo3zZ9E80wK{$9^F$& zKE;~txY(zbe9<8NS`1u{E=Yq7(C7>4RJnG8BWN&huQQlMEUF<#q>y8Yi4^0&;)XKz zX2)WJ*4R8Il&Fh|%I&D0`icnkFjnHa6rmTfQ^KFjY48J&cYxV+5Fd%Ru#P<^b3S}a zIjYz{(e3$mhlnyx4^0wix~x>z#z9Pk0?=@Z=U^ zS`>PXs$_YF=u+!BVoA8u#qypzMMrKi1+ge~vRm+4SX9J0s<4i`7^Y-lXO!&gk=p&} zNf3^aK@j>7LR?g%h#>c#o*?&AL}GbQ&vuW7riiHao*u4YP~`76X_4>kN&c>(d-?5q@POQ}@TS0_t%BsAp&<60)@<&)m7R0nKFI*LY8Lf3WMkWT zJ8!}t6%Y?@&nsvHCWx~5qrxp|zTw4S$2G*^uFlzD!U@#iO37|BDC5>qvP!rtU4|U7 z>^6nbvSwC@+z$Wh#`kwOezz9#iciDp_Jg8odaX)BCV#Ag{T6FJ$~{qlw7Moi3O|uG z_{n@Dj^Yy1NN~oG10?z!rZUPlq4i}UG)_un!{P|PAM~-F%agB}&q<@80i&sI$*$Nd zcZQ5VI&BeHJXR;?@h;Rwu4NfBY;(%MI9>i`oYZa`G9v;+Ii0G7|sV-!>NdA%saSM2QCWGrHr zG`Q#?+@8Rkh$R*cVUE|Q-VRH2!V)sG0kSmh*ckj-N>UKzoOj5f7!QI?U1XBw#$<+I zK!U+Z+ndZijcO93MSHIs_a%SiG3&~ZZ-FZpLLvj=-BY7Kc&G8vPPzt2pV_)UrjLsv7#L zMW+(+YBVK{6(dv`T8ksrW}MeYc0#UH5U|XW5M540p;G~*fMN#At;Bwj%;_8;qX!*y zkWAR*#M;6++rRS)MsAKSML^5eobA;46p5FNfCzSVywu)hyd#_eh^qSTUWXwelh4Ia z%aB=}?*SSX@6bl5bjg-t%^Ww=ZI0ixGM>A55E?if7Di4d;=RbKGwiJslA!oc1Rsfj zw_GAiRwXz{B$3b*EJCfv?^!dhv1q8yiYD>UKIlXrSA*I?0dYCdrbK#$=GY3C2CrCJ z*?zB{4>in*je@~G-)Ciab`UY*!3cGZclE>#H9#MRjVa5RMo!+QrBEftJ_cc9C?g0< zU|y=c`xu#+nuew!et(eN-kkywi3joERCrX;zuO|vL;tKA=NN!}+aekc4eP2wPJ4&GsRY6nld9j2t}bp%l|KoHj^$Cc6qH zp_0~M2@b%}c>sE5=IA;vqLsdGecxsAEnvQG{pEfO9+jE1*RAIkJZYudrIr5E^~vMw zT`Q$b?SHyH-JU*Hf%YhCTyI#9i24&{rBvHlu1xyYuwvf2AaxdHLZd|)!@M|rY}+yo zMQOBKdKx+!tRh2hMKY>0fEX?iIicDE2=xu?gKTaO7{nXa2ie>nFz7d|53;#EK)!p! z`XHP81H`#EtVg~(5ynj$KfAtm{lHx-$1QsFWascU9nAC?^0mhw7=gNwTuO@t+>%Rw zc70$3R>S(-{{OM}Cg62l*L^SUy&wo2P!xD6QqW;0sW) z>?R~g03>7(Krl$A9KBbMaUDAzlR9HRJ9&MLoxH?poaDLA;0#UT*zHTxq_s1>wi#ZW zp(b4Ip+f4Ac<=Gy-)aT@$PfZ-h1t}*Is+=HSIgop-L`&|5ol*eKr6E zkRRIGe0zm(z)VA+$uLP?1hP0gD?J*drRb|vZP!R=I$9y5+p=_mR~tDqqFdv0z>AB~ za|XP)*oX2+7Z>}`)^HQBMkB8Ep{>|Ge?5{C558q<^R1OH;B3|iK4*_>2Hs$|BqA*L zRCAjL-cVq^2X?3lD9P-d;tNX%MM8tr{TxH(w)l+QrmmQ^y<9J6uPmoTJVM%MB zP7YT0YR)^utImDMBRY{vGcM7}6Fsokhyid$*PSj}XP|*}Px5K=(~%kpZ6E|HU!_`D zJS*D;haXhulw2thK10SaiNY^dJJ!?l?6c1@)dJK|Ht)k&=^3dF42@0tge0h%ZQUjJEV2n2Z zf#Nk6s-1lk)!Ia7wZCtoHo<}E$=c+JG2HB)?5o%NMki}S6VMu- z+Bf=C_3_&1AZi9|D9i;{4`6=Pb{{y`bQZDJIKfJl=kUgZ5e)_{bP50SD+SE^fcuS~$ce&(0(Wl`#J={)Ml6_O+ce!%5#TMA%mOGMdLw)s;r%v|`3=B<7 z;NRbtZ0Q>rKhf7wEVm}j{X>&|q|$Clio<>6-`<`igG1CG=u>N3`ro*b!Q`Ne45sUv z8O$San#fFk`etV)!&hP^y@y|6Ca*A)Yi1_C#LG>Ck!|RwKirwI4gK_oH)U)?KmFmZ zjBV(rKa5-lwxOSI=ddN;(n`~Cq4JD0wXj94Yzcv6L_)A0)2v-O}ky13Hg9dua-x`apUMjoxD%9f6#D{01^ z74~&o@y<#$=2%R(OMtOVM;2;D)osZZeNN@uij`P`yWK`;;0bGrS9ca~;*JN6Eo5kp z3XXO8<+_#N2X&d!L&Z(n(wulNXnJW%8B5it`2L;coyi-l7Yd!lj>_ZJamm4kz?co% z)LIwj$e6TXDi7`bbYki>bR>4Te1_~)+GovhX?YFOu^|f6bbII(x42R#SyO+mXx+l2 z_Z4?mezb_@aT(2EpXL6I!=w{Bur17YZ3G7Qq%g~_2@WKf0UG4nkk*DB5`}Ao{eTNC zvPIi%s9X~)xnmmXHfRLx@lfY|_Huvs0IXCzQs{ERvsU z4P`G{QpW-MW69^F3{*ZKpG$;k@TmOfn%NRK-iI&yA952GMO-?M6t`7=vl*+((uFCv zcSfX=P)+yxdd6{15NNd!GeQT-ZAj5*pv;2~AJI|d}tUF~Q7)B^@) z^xQ(M?sL*Pg6}BN^U4~B6b&r+PScX;2xFKYf)u7t7*(DXO)qlI+^iWlW}!*>pc&H9 zfY?yZF=;3gmQi-ae5exo%v>9iX#k9-(v%6AJZKBqVYIeMuCZuJ|C(Ph@~6TP#GX2^|?jyaqhx`yoBOy zTu8?AbLU-N3!!IJ2=|gO^Rwu4@o8Q=j~9c5o!QYfMT4z;%w?WY%9)N`dCcKXb33!} z%-r(gf?HLXXU%n>gf9Dx#OvyXo+T{j1)T7c@cTU#Tq-&!smFYXYpA50UNH^R5V8E=|XwVlvF z{mKO_SJR8n>Yz2v6q&ia+dL-ZzoJkDfYFuLiwhj%!krnNv3XJF_##r}V5U=Gm(KoGq40@fX?VQ-$N$Fum?8cj*XoN7G6n z`QkRyhuncaip54RAUt5YD|4o$)Zq1eo|27XO@fPiAQY>nE&9B+Gf`tgW zO;RSMM!;+n4iK46-coxJFC_JimV$e}NR4Ay(FVaim~cdM0niSrZ9Lzj?}0gRKm_*t zIks^y>2|I4KuB83aN()TphknTM`$xQA`s)mST)*WYc-VWo#7p8hekwFeW|2$gPL|2_#%{I zED}XAPt7R?ATG+^#BstV4j*S{B04@etD(G#dag)8nI?%G$095e5o3#YDl#P!Os6_| zqBc>T7&|_RMr#OFS9QET_5_aogVp}0csYb_Yy7EtZTQ4w^~Bi7;81-6{nnr~UX%4& z|EbBb`UF8xK})7L(tZuS0p-Sosm7!>L5q@8m>sCrMh8Yt4c1174^(NPIyyGV8Lf7* zhBAcAXa}s@jrF8jJ2_MzIDy`+ufH}@n|#VZIbNF_RcFV?>hks&@2gMN22PFi)rp6# z6Wcme)yM{G69XfCwUa}GYSW&ee&}p^#8evhaE#@r>m=@SooVZx<&u8-!@HYKMCFHm`onvg4n$3;e)_|E zo4V~GI#d1hhxcV_68-dtdz)TmU!wfb&+qEM(v0$BmW{9SA%z0PU6;)%=WV6Km(m?u zs_HJ!4W1ca;k?=BI@_6B5{|$e++a~b9I!2lY#QOxq5KQHizFDB*dS9BQL(s5DO{*# zem!!e4LO_Dpt4DF+j!uu|C#%2)F&7_S0I|eY!)-~~*Ph_UPrxav1Onb1QkuY9Ei<%^4*1~XG$MB?PP@81 z5hX$FR>|Bs##=*6u-v!IX*)nlzQ60x!2<^m9whTWp~GUIccp$m6oLy-_0TbS+u#>8 zlg*erALYR{d*#x~%-XcvJS?TY?T;xKZs^1bqr1D?{6%n9jv$(4F8?MS?{tv$Vm;q< z%XRYa9_MEj0k}EGFG}jMsW!v>D$mX@0bJs3y?mKgq3v z0ssOo_J1$}kemMAZ2GhLviZ-7_h*!W^z#C#U@%T`#7vy)b@an@#Wzj`n!kwRM;oWS zdVhxJ@JSe2HtDg7&qJ=l1}ezvG~ziAKm&@i3Y%g#o8Iih*W{-mH<$T78t5pis;;jz zgNL&jOmS@!$f06pl{MI{|4h%!+YzHW&VA961Rcq%Li)xJ_rmyA9>v}NA~}~)*F1XY zAZN}zeN!#=hVN3ttM22lC{d5~xp#GXpYfj8O|UheL??#a&x6_msr7l{CmnOROAA-Wv&0>Y)4i_nR53e$E{;rJ1V z2VYJZDCv-$ifikTRngF!aO@#|*%lK$ZPQ&wUg6r`BnK0Sj-4f!LzGa_d3c2ge^gYcX|mR|cO1$!7TPkUZwBIKt#wE8 zI;3{h&bn4Pm(3}_&Bl|#m>c=!o25;N%?uOD*HW5o?MQw@32V$U@igXyf5jEpCKaTJ z0o_7=>XRiRCY+B09J`{?cGuxUM-Lo*@BwXb`aiqtV)g!Y4>`hy{NUZyQBEYs)GC~p z)Y2jiol>PyGZVX7CD!4Ag94%lvgiCsfge2=migU#q_+l;RE6SP9C`jIns#ph1VCeVCrIKNCv9q)*GbS zQi=Im?%0v4wm$XILUOZfk<5aBj=KX0`$PO%UCi6=D_1u2U)?vTaup3)CxGlmenUJR z2`(5Deh0!z`CwAE5G^@Ro+i?L<@DO}oT<{<`ipxC^^WxIATLiX&y`Ok+c1xi@7<&y zsn<$-xA)#16-e?n8nBU$%$;3E9Wh1pVg!x1q&{$ViPZKqVvf&(e3R9lbD(}wYV0bZpT*pH%{_gw>F8&(VEgJYcFPzs{JSADymMFfxw*jB- zgBRPVZ}%#(tduKU*?QV6Dz?C80H>|q&cm8)j9ORsCp#K4P1tv{_FYHA3w?|SFbnN8 zlE5d2WnV z?0GZaZ124%KL-uVe=PTLy`gG(B(nH)2u$Dv`xvYvB&PZR|(S}$m_g~$C)j7srR{E2hHp9{jSsRssWLIb-9f%?0g*4I$ z@#Xi@mqIO_Cz2%FT3=F2KV3?;H}0(EO43R?9NZWdmjmla%i3?`V{&?V%@Twd8)@&o zH%~>4tr4ZNaK7$eBPwQva&NLr_gSA_T3oWET+@Etv{PnVeWzZI$9EQ_zrua5xZvj6 z7*5LJvNoETpC>$)xMu^pz4w*~lx;7v5XXa9y(3h@6JUN&RRm1d!0C`ahI`;`fW`Vw zy|gbwG8dIQ5o%$C7ie*zqf-9uyf-235WXRMny=PKhgDKDQtnV? z|92OXTQ0lJvp(+|z??QZd3vPQU&o+ydaOR&H(GmRpNu!_+?H`c9vB%rHHbIz)}+)o zIDs#6lC+GU7@HiMz#I9-q#ZlW(9q=RCu&1a;+DKEX`MJRHa?E&g^bSB86FzzXp#Ff zMw+2IeLOLAy06x;b^rNfPXmy-Q%iY&a_>4A2Zyj!jcx`a;0)tYf2zMD;pl$jc;CR| z7{gAV>>K5uddE%2UYB&ZaF{WPtHyMEd#f>#Ac&^?@6In6yhC4TrX?xAFPUe(Jw! z?{2Fn)O*6udi`_B`mmICpOo?7l+owMX@;p-0t>Hrkr651u$F8sZ`t1T$~3DvQ*`cFlt+}6}rNZ!@%;VF+5_gDT}{siVgq5abluj=w^J2PgG8mZ0q||cg-OVrCOpsO5$Pd{aivp>v*V$IWBMc_})|b2F$K(buBYJFHU8Ni9P)U+>&`b4h*S{LDP^;pXqPYz-RZbT3$L=9kARV zxC(kaA}YDP8z0pjXTio(1&6xCk~|psdZ|UrL-VV912bm>AT5&+l5L6mFdcR3#BpGC zkxNlK&2slVBY4tGA40sq&wRvmw5>+`%Y38BaUzGZ^liZ06dwD8N@8BJr|V|h$Gzm2 zsM?K(@{&x4UiHk|`A2&vaCc&!4cKZZ7|^n4*#sgCxg%TjpkLwMQg@(tKlbx$xUq(m z9C8PDDE3$T7=nmXbeBa{ideDzuc1}PY0O*hl#5 z8hV&8nv?P8_1#)KI;t*e@ZHHs3dKMyov#PphWoW%V(`EOb>czD*Xrs>> z3o~E=6lUG>IKbOt93XKHkHt7Z%nFZ@r`h5F*)|?SV;ExsAG>ECTZq{CK+|d=`2qn% za;ZI8yuI=h1tT!Yej-1aNu5|${FKf(EWJo-FpM5_(UODPzw7VBoQxOX_9;dY96y{8 zLu+u4#pvO%$r8>>qPBdM0mhfORydUCtC$3D-G*S6v&JZYrGc&Y_;2uVve@dsHORJI z{u|TE$vw9vKSR2Gc@Upt@IP9rj`bn8R$XqjfC|RtIKXJ<)|MAHmb^f$vHSy{%WAbV zdd@1yHyzxHM%N=D+C#9q$Z%zmS{p~~*`{QKhO#}WAq3(UFp1I!%&k^|#tlqdTNq@h z`FIgibG?Rh06!=HyDA>g7S3@-2j-19(5x%2D$Y9D2$)fybwyvD3$soRg3>u={X4fX z>-=6Jf%J#A7|9bt(7ixx0uo=kIjNXc;i&k=8Al_iB4;8wmJb2nE1TiCABN*0< zFBt@o#b?tt?IWU&Nb(VE{&M}lI3=DY+c{Aba!8FPR&R;GaN}7zJNvTCL#@2rxS7o_ zUNVnt-zXFt5L?NAY+lTmwO6x5T#HLnutI?o#=)8jr#<((m3ubP9~N&A?6z!*OP-uH zh(yGNcrulU3w2~Z(Qs4T!%XM^wV;SBIhJ?N&EZHro*b0DN#5Yq9JF>fjD((xOSDB* z{N61CPux8C6hbN8Z&$5&}r^sK78<@-a|5ZJTo`*tP^(NVv_J9J(r;8l|aur1gx~( zWL%8o_NA4ZtH}fI1^H~#|5B*PfjwjZ$OVVk;B{jFw>1ZO(035?j(E294rO==-Vx6g zk5t}PsE*8$^+}QenklGAL0U{;mN_Ifbu>DO6C#jeCk+eO5JxKO-qR~R7)e%o(uR64 z9L%f|U8+#6XdstE!*h(?P2zHBc&_c%SYrIoam{9U$D!sqvVPt`b`+c)TJ`c(y$bJ? zExlZNzIc@IPOXcaxj8uSh<40MMff3W+XN&h;q({-DxeILM(P^6eA-@wr&>eg>F7^RybO<9UaNiso_irh0K0)l%4I#@YIB4W$K(d~3V z)EHrZ-On8Aw1LK#a=gK4*gZAP3hl-{Y)VNX^%)~oZX?D<5)}s58jB45U4^!eSR{eU zy9zsRN**#q@bWzcVvzU8=w?o8xU5F*9^uW9lXj!)ji`DysuEaqjI+Tq%wGiYw?Iz<>zA@r?C&&?=Ihi?$4%HoCn>X{q5O2=>F_)*F1O+q`3MnjbdF7 z-J{%?*1+jd#iTRcN)ObEV`!y^@5;sihozW~fm?b%zR4J52D*F?ZS+8`IEFTQ_;@yk zHhTED#&F26l$4vlM@#LlMl1~@5v)@tr6W*S9Cfw@T1{yGdkW#g=|VA~{qHHF-wE^=>o^H59CCV>VDUx?601x z*TN17Q1D9yFW^@Q^Fq{9ko~4|h`mx!14&h*X+tM1uhN6=;I$MzQ~jfd9zOWc14r+b z*eQ|Z(L;wGICSXX;W!%QYXd;vivX9=e7exKI}Ba9+CE*l<+fzr2E!)tnF6PcuT8}& z4#x^0XS+w3Ut(k06yObllZi-Oa|_QPE-x-$atTUmDhZGgG;I)c7eNz6e5TOm`&ZF6 zh|d&muO>h0hz8QnYE}KSg0g4GpBORUkR+OB&lIAS*lJ#8Qa#h&9HbSIA>^c^M+m15 zx!BO_(GGX$%o0L^&PAd0688>7SwdCjQL$o4mzWtPjEhqXAcJdi@I_udmqQ9})FwAX zX@GGsOdyZL)IRjtLfg$@26Xe&XA70vlP7EjAjKaq6mP4XsN#2YV(lz)um0wx(U;FQLd7n6n~5ZbGLyuf+WSAh1aA1~~=HTjU^ znvXwUDE3s|UWj10)ak+{8b(LPz}VoBMc7Tmjd+^NP-LUNqz66%4~--aRa24=QPsND zysT%6L3)F)3qbRQY_N>I^?UFvMK~8n%q!@N4PRqTK0Hov2TdQn{;EbiC)l zD*Yr-if5br==w_2UCKm2AhUQ}Ce$fHi_H(-J6`S>q)=0s}Tmo$e8Xtcv z1i_FZK}ZJpQlZ@imts*ez?TZIIux)Y8Q@EWBM&MMk+?QOz%LiLD}J@=CSn2-&_mln z(oF;DX>Z+JU(>OX$y!-E+e6x!ne}H!ObZd>Hpm4aBDqMW_~k;|{s6ILieD~t9gGko zRQzh8cyKd_iO`*dT7#?J^#<4uxsLJ#hyfx(EGgwz3vF>{l$7$Tg#$fEa=L}C<;#Vp zzeY$|C&`&8zkbOFnLw=Z%Z1jPl8?*vza*jHceS^ExMb(y$a_ua%c|5q5B;gdZm4?k ztQ|>2MNji6dJl#S-bQSZP1zjF`^4p^Ol4+lVgG)q>-X=Ml1ZC}?01WvF(g_CAY5Cn zQA?3}XLhS=lE0pl^5x=~XnASs?q4m9`EW2Vf`#6P>V!rP9^&mVCWmYYH&=8n;V99vG=9Cn?E znIcGnIdYPq$PE5&q0MiRqzFm;Zh>s7KSGKlCX}~-DJk!NR|d==tJ;_YRUkH)K}kH< zXP3-Axmb3!F!U=)!DmS9i>^efA75NuO-K}LV zu)8lJP2|B8l*GYCj_g2MP9)EZdR<8(be#9Fjnq;lb~GqVQnKhCcP$W?@{;KbV(*id zBx=t$s}O98EZt)bCP%Mm%n-VPxkETEu23{O+U<;oB2@O563Oo{B14G%t3vVaN=J1< zLTe=QuuYeWx@wsZB8`eD|Eh4youMm~?-a>i+zS_LF1P$`q3Q48V%Me@(7{Hc)!!Cc zcN#R!;$eSxd1!bKG<@LDP^9+XMQA7j&EG|6wv=1mUTk_-aRW3s_HK}(0!x)(^!8$a zW{aSCXYsPQ;XTmsfkQ))+V3m|+)xCXcNW3TQE<~zZh23!=^KIOnl%nWkEEja6uBW& zlhq=C-g|j~cn?5)-~dsi_Io2h6anbH0!UlV)^f`?6`MW;Kj>M*KDzfDW zoUH=qgO>+~_khC(4h}_Xe=veW5pX^j@zYvv`Dn4}GaK>a9=(^FFbOUnjreI5K;LqC zfOro;eBc04r1rN&fG7gcw+Nu$li1TLQvc3k@&3xcD=661qXn}R;0>%04jlZGqbP{J zCDpy!K56GI?O4GCnq$9~DTsa3ycXi!a_rk;(%PL!_QZ_^dt<5<+tGFTm*ud^_;WW3 zg{Y>F+yPFZ?IGhE6ApJD##Y~z7$;a^pw2HS+PHW7E%6k=%6As`?N8oMx-+l>!}y+J z@j&J8a#%6NGKv(>zHh@(uNtl2Qm+6%Hf|2`0v^c2X(ram^wb%yGQJ+a!sbM6&;F9n z-|s^rxmgZ@Df;FSwskVebk}HRiD7^-lavA9RUH|@^m;?>An)LYohZ8X(*j}mEIy9N z6MqCB5qTn-?{N@ z@Tnr#KtFGUN!1@HazT(VGPm6&50~zSr=YF7wld#SPt#&yIx@@ecW948tMzvP`w2ORFtN~&+taVS&6dw8Px+GMUbJ$8i1EomJ* zd$?ZfY|p_X=Xz(SrVc%PXzJm!N2d-QJo|9(;fH%?XC6B8P;c*p51%`7QSZ{$zoboA>CqRok5TEc3buUaK2Q$y(fDBO@67^dpLQIuKQ3OzW6sq zZcuqkydoJzl?aE6l%_phD~CYbQD7quc}QX8cLB>w&%s{7Q4!X{Nllt&-HIUhlze2$ z#xWe~KAMAGntMQLOM#Ub!zGM<(~7|g^#4XH>P!G0N#@sz%?B&vhZBqyL(vXj#0{A(Uc$NM2K)= zld5GW(C{SK*zwVrStW-I8FOhR>sPv>ujHpvd*@d)l^@my)GkWE(Fz+NYa*r zX-fdgwIzVa7=F9hMp%v(i!sRGF5a{&`9*0<+J)IaE8-dO+2$)SGr_#MolBwu3hj*1 zB@LWT74iEOylqVtuA_Wl5$ZFT)_PLY+KOj+V7yUme_>iF z$6=~Wi<$;kw8{Zp&wF4SQJ>!0dBeYv}08ka_*zXWq+9-4qF!wMAFYy-x!Y8 z*hB{9(IaGg0nmpnH;Zx;MZ(j82wHMa0w~K!E4YeKWa<1_5myo4M|B|jdmV`0R!U`h zJiAFqhwUu&%XgJrWX{0^EfWB=lM3Sqp$&dnXtg(BIlit zhy(wC%Okcb1yI14-*2Iw#EMCRoSvHq3^^m<s#KM zrcXsE^W7yhefzB{FaJ@Al=-*C{Hz!Oa`#14Nvx2zB$DUjt-=v4;eAaJPlS7|B}(rr z6_d&yVh<3*`ldMnta8d;IKQu<74c*~+!9*RN_k(YwJi(K>hakSW zRJ^frV|C)fqNNdQsBEr73@}tC4>_OTuszvhm0=Da)991x@XTUEJ#z=j#@j-@k7>Ne zt)AS0N+hWw_p)DeD5XeW4K;6c7f;RYE8TG)dS+%So|+>#<`M+-0XjV0X_qk4*Fe5_ zApVn*!WAnAb$5i5THr4m$Tjcz_*$nn&HFzoZMi-9T0q7%uiX5J635c+g#uvGqW7n;>PEs!69-w@T9O zNWnpx8U9byjwKUmt#9*(PuMf^DBL7t5z{?=nhe@9F+GNv zxjJj>QfO=|Z?>E$)LWLUIdv7^(xT#^ODBr{_JJdMdq>i`6q{{RvnR+%zvK<`zW?TA zmzv%%z*Cbo)LL2&2o{qiOKnTOji)%}Duh#i| zzDawtDY-#{xCwZwk+!=1F83#`VZbp<$hD3*t=IW|t;zOmNFq@u2Y2xZ6u)(r4G8i} zNeJ2!ax&U75@Kr<)s=X&0}`6BV)^zYnLWK?>5BtN-dJy&od^%Sw>7URvb=$sr@ZE^ zN!u*BCf+hLO+^vr)_UvgaWAK!KzpLhb<`|S0#%j+C=hxM6kduZJ5o^MIuIzl)FNvR zpztaKg?H_|Yl)!5dSU%+<6Un3*kYWWUz}Rqa|3T!AG60*D(^~KW>248T%6yto#(Cf zEwlX;d{lPd>7E;TzK!qub^B>~T)2=6()8lRJ<6Z9z4!1nkeVj6dt`2Q=5enI)Ztfo zNPOZPIWedAbkJUV?}2MMON9;jsp?T9mNU2=NK^9ZJ}%cUVhGC@h%gxEoMt0#;;OpO*#HKvMmwAA_EZrR|>@UB+kd(bn1fqsCe*FQt*8r(@?%50w9RQBGME|xza$^S1 z>(>ZZy#B!4Zou4J-nAYWv$9C_?9V_qPL_`UQ8z#71C21nh7I?a#uXh3-nd#`z8o&swYi~B$Mu!_vNo({ zzE@Gq9gSF>Tqd3qS@Gq=?yMpAO!;dsH{LLw4dYyghltz#&l@I*`Y^yFM$1_5c4T7{ zn;KtRz5c|~X~Vg#a`U?37^fmtx|kIgQtw;`ifj_sADFuhm^*rJ*%TP{DRADBY#p9i z)xK1|rfsW|rm4Nm<`$TC)q1a#GhTTv-Oqbw)ZN!7i7Pj(^J{DN1@@lf)a!b$?D#_8 z_W4EpK9nTn*n>wNc)0)Tl3V%easnV%-yPXh(H0Et5gk3Qx9LHhX@0?9E#5M0QNzcM zO$7DTv13oTR_b;CX2i3ty{}kEejIO#ZROH-F1-68xj)AX&fA@lpi7Hub_JQz1fWnykB7l>RyQKd zyhT}nbd`6xJ*-iM1+Fm6GnKDQ%McurQ zW2I+=tE@&RUP-t1lG3dyof_9wcQoB=nbio{-@(;VWI-bX!_KB^$cMJ8>2bSxs=Zv& zPfwDzyXlBMq>g_2!^$NYt$|PRvO>o^PwxBYcj8#G|xfn-b6DFY^SV%)5P(a7sEjPsylzjKD z&R7CHcXvG^LyEq{Kz2{_-j-xX(q_dU{KDrt!=qpJabaiZE*>sbemaecwq$eHXJGO? zTUnVpKhq_e$^tnw=xkioah!$vYU5ppdLJYm3{gb*mPX6@0lV2_*@SkOd&qAWt~0Y- zJ;tZGSUklKii1*j%btJ{t@Q3&?u{kz(|zc*0Y9YoXzpq5jrb`vJAUlZyBt3lULGty zQmQ10r3-x7<_UC>yI z=elRQnQh-3#gOpB?m0WP-1Amafj!^ZkR+qi9zLqK`=9UJ=V>2BM98vmqbuMI`*G>9 zmP)`Iw&K!bx9*K4@b=i@zJNEm9QQR3M7)&(-t5t^u>d|8E{>Ke4_7DT21U1-$eNuc zok@nPZ*0&};7%tKqjYJw<+cEZt`Q%;eSa(g)bP=P0F<1GPc)y5Ks5)T?9t-}6ejG~ z7f+Qck6t@a@gN}VnWugV7s#&)py=N1*Wc3{O91xzM;{M>$-lSWJQ)Go5&*MD zPZ?mC$KO!=nv!MZfi+(%!&FK$-%4hD{~71zORt=QiG98FhL)QHV3^lSZ`gBBECJ>l z4!$OU*#ekPHUEPMW=jCm9=*xH#2SC5I8&;ed|~T*Bba@Y+^o3{P)zitGcC6S(3Fer zOy#~<0?;$Pj|D)t0_arpbOdy30Ms7+C5~+@bApjC7Qe1k`Mu@_P@{p1joLO^*4R9* z>&zu|NeWWuCiD3~1SE-}-NLgv8Q@VLgLlLVcliDVoW;;(SG<>neuB{RgLc4AnZ@2|^ z&;Vm0j~V&*ml1`LqzN*T1SnxHPDrkzWq&mpq`Lu?iBq0DTTGZmAdJ(O?+ebkc9D(D zuk@qj^kr3qW+z#tO(50Z+6v#DXGWNYDSTK=v9On2Oe+vaawo$e^jiK6E`{Z4+QkEM zP4UL36;BPVWRo}qIo3nRkNCCS3V!wFEApOMUgrL6n5MG}5s2J!J+4eZ{*NbZ+;OJn zkvG@Q+rV&WzrM6fSV-woOGn_iZP4ze9k<64w0mjqkwCj`(C%~1Umt0=Ezqt#+D7CB z{(x^QG<|acb0rZTNZ?A#CUMO3>NUR|F;h(`IUQRvMR!*=X`N!5JCRaE_Yez zL+>aQJ$p-&Mc`5F2rVJV@^**El<}6T?7u z(aA3-&3SqVi(C(PP;mdT#-L*B*)Qi1gQi_?~N%>=oFCNTPS-_BSiyZ-~Gvyfkf4BD&U&OmGBCJ<`6jR3FHyB7S|aQ1pyNO+_VHp%`gW4vHTv1Q&YVQuTuc zTO+R8EK=F6{8&r6wg_rAX=mZwZm*BUww@A1KC_ zT50JcSxf9Q6w{X2S}3M1v2lEqe18EZtyYS$CFKP9Xg0?R2K#6M&j`nsSly9~TIP61e8(NHVyX>rQc56n$#kNAY8Y4$nYDkybxesN5>2PO8!n z+1hTwsdJK5wvL!H8AEwouRy)D!%%3*CyJuAOGZ!)g(97PyH?O=LrSxc7n;7CIQvf( za_R^3y2|zz-Suf{V#9h08=GCf8oW!{CZhAXrAgv`O!$VM&_(f#DAR7(qLU^oTMILD z%hmI2IbExZU3RR`>7ZB%QLAN%HCPDZphDQk3$2pjLn5*xMW0@ZOvEP& z?J>obnC~YFx5k_`nut#n?z%hqKH-E6D*vp|^nKvuJM%a(w=ww0!nvuX6}zJcS8Jk^ za5K{pRNG~Sp7kU4d>2Z!pxiu>ElIFYgc6v(hy$DrPHlx0nIE18Yeb3lLD3ON5u*BJ zTptwa^^=9N^9G6_@RNmGbVgRT5q6bNkxS5~f)XuJj4dgU=~IPvU+%o6rB4-Zc~$(F zmOfRu`yP~YmIdMm3r)YxOgxpN9@CA%(NoQk3w}bT7^{va>nRANk~?Y+?|FqRcz!Zd zQ3fQ6h5n!x@pj;6V=1?gx$XaCg=@`F=JlsZh|cR473IwQLxtv7S?HCO`G5x=BxMgk z!4DPgtfn>i;GY+oZ%%6nfjlT@52*3a3%dk@_d)rG3(Z{VLrk5T6ry;rJ$qnZ?8u-3 zb)P9T??^uoY4BiM_JA6nDcsnR_QA~jNWMwofd?M>rcUMT{v(BLH>5QngC8w4cce{f z2jM|`_JA5cTG)PLT7&8Su{>1TICzjjCExZR6I3D|GH;ZdKNoi$N_0rkDVQRaKNoi$ ziVXR4an~`1@Dp*bqeNATzSmKt>QBVIjv`fmBJOp~BH5qJdX*4DG4?9d|76yy#EzfL zdZqMJQT}SSq;nLV+9^`?rwZ*Ze^IoLk-vPb;QyzyUbU}NjJ;|yemd(FzCG`<~O`be0NE6LP_Vs_6 z0j!OjVgy(l`M=Bn)<*s>Gl1F1e?CK#c5aFhP1?DCK0}js?w^;K>S$u;{>4Jkx6S6F zwrYy8S8dh5nDwfy`WFi~`F`A7BzxBv*i-`|lt+tVM3bVdx!xe6NqMxsP}nW4uL!Zd z-2BC?*LJE>jJ+xX`iohw?Nt3@*6TKcTVvLo=HfQ0Qj8ehM%6E67~V$JFBQ0p(tEw3 z-2AT##R$?3RHf+BaC7kns{ZT3RzC<(r0Tyebd*EY?UvRolG=8vlI1M+x}B=Oob|e$ zs=u7|dSkiySE7{FT)Ytqp%}Zlk*dE^*dFnJBUOK;P;mjRx!7T;$?ggm?w~4}$|4Z> zLs8uAf*{{g^;ZkkPC{vg;T_64R;>2!2=SW4sJe1KlEn@d2w$W{hVD$y``Py=3fWQ(9%v? zq8MA+NlU+;!L*Z>em#R}CoTPY2GdRD=HH0YVRP{&TA~%YKktj@{+2*U$~X4oe@eX zQuX%>_sA;MOp$N@Af9e00R%;#Mv6522a!lA($XJ9BBe-6f8eJZwFHm8o+!P^6`=#uL{Tshj^WgGpyMim@f_0DqXlq#fW7Gnljk{9y(YJHQ`B z*>p=$XE%zmC2a_Q6c-L}Y3YyR!l6h@e-vfYE!q(NI2)bPKU0jeqYdGYv)R#x@WxZe<^I)uCXX;R2kj;Fsu^I zP&Cq4kv{)Qr(ge;mwz3$99{}qiUz!jeEZi0VmAF-O8+(F1m~r|qiCDDiuM+f)xQPU zzX|FvUTWo1wE0$%Z~sQZs(;Ij{%!WHmMX>gtwiC!&AtUi|1E=8Ym;JxS7Dz2&Ed85 zXm2Yvy%SF)om#bG-ln{8@01445}&<;%q^8?bUgsap%nkijgg-s$@JTg_Z zE>nuegWS`YGt=!W!Ms9~=00WCm7r1r3Wft1KI5KV?H$FfE`@k{wRaRvek?YVUhUn* zCOKAVI9j&vR@NNdCSY09-cu}AxJ^Jhj5Nbp{=gdnU9VJMZ*B60<%!m4(}fXFwDz9j zb{8-_(b{{8NQy_Sf1vqB^?$GR?|G)&Xe13p&}znfMq%`xwTx=c1w3onHx{?WF0@p> zkuK7}$=|yxxigoq#e?HxR`d`rnfM2IWzAJ$<_5z%$xnN@UxW-fOQdV|ulN55C(Yw? zGxO8^;btGg7AnVULnDKy`-e{SJy9F0uk$!3_+)HcH`exzAY)Og554|Wtv)n}(>b@& zj-8ss=y`fyuI))u8%@j2azn43Jb7xeuYW{=ESw-ujgHj^hp5i2xD%5Ial4Wo zqg;nObaH(1sndf)$NNr=Om=LwmIm>EuK`@WqxINyvb}Nm<=dm5UmR_>4a~FsuI%{^ z-7LF3yN($A_y=+1{l$)^`VH1-`e-THj)o*QOqKp}1GdJm`)#d%bEkHO?M>%jxvcdS z@4=VkJ?MUd9ZfsUc@RIsGB>okBj8O(N)sOok!*#!9%;&w>@I zW(azej4p55m|rAzsQa%XJNp{Dh;u@>PLeTB|GkFFIqv8612c|brgxuLS6AoNpnKC^ z1*D9HZr%XyH-goq2{|#l`$5r9&N%Phw8R+kOq?UXYCseYSG#`Ww zR(`Ws?OR~3$zC|c#wCi;mKx{GDd;?TC>8?w>^1GSXJ`r8X}BFun;azLra94+$S3Nw z&Dq1-z{nA3P01EKgQZTPPs@1{Uj?#;`(2uiU`68Ob_zTjqyS#Q zB2HGL*+*mQ;#{kuc`TE?2BK8x_)oT`EWZ zWkF_g*#7;r0A#^rYL|}&lX)PBE!7XK7RDf{GTJ7aZkX}^ZcAW?7 z)UvjD_BF$<+(~fDSu|&j=x|PBIQ*#rn(IaU4kc!_7mf7Ckvndn7Oz`R5w=7niu~ zmDeN(C3V;G;u4;HW(szQIRpS>91UlH(t~79`6-8=(yM|0hYENl`RwIDjtnc3Ng&(k zks-ph0YE>>=c$bIxipuIS)L$~!~=E8(EyT|B?5*Slj&+2>oHz4vXO^OySPuuW1_lu zZN*d8ovDpJL9pN8>Aw2#sgnp!XXFp;!_ySJIvpOzmeQ*k-hcDqu{Qh3O7ovL9bS$L zUv-3_7tDJ8PFrg3XM)>{Ev$TAb!J7&Q??_905>=Rjop) z6Nj;Ge76J7b%i6vj>6;kY?H zvwWbz>sO!KV`~Tw$;P#ek3O7KF5+=za4AH%yj#!R|4F?-n_gQWv95F2W2eUnImH-S z9I#?;LP8N3t8>xd+Z!S z;xB_i&#)|8sNJlr74N%~w-#E-Ep0KhTzCFKbkK|*n+iT4*O(f$SAllyMq4q+XURIJ z`&%Q>-UDMt7E(s-G$<;E8-ivsG}!W=7KE`RKPTu5aedD+70wu^!kT)-jJ zBIj3?&k;UhdmB+6YcNfV5n)v+2j!f*838{Adr7=!!Z?E4Y=i*pxUi5)QK7Mj<*cpr zmKo-B(Ovb#Ol^e9pam!k?tm4-CA@7IgO5qcR2`R0T2^t9Wxs$dL;A4HJnr8`m@u5L zcl!-HqL@AuJj0EYb}<$B-D|hRX><1se8HO;mI)S2?u(LvG1;{RD2rnS9+=1#s&;B= zT0*`%K}%H2%ZmGOYUE~LE+)afWHx-1B`MD(%tVqT2BdnXmMSaGn$5TT>AIk)(z3;yP!k5VrT;mQ!!I zMns==AGdGFg<=1a8>z*g;CfL$K2|^3w>}jC*-9+?B3hx=q`5Z!#1S+?{_6o$L2xKN zJB>n#e;?>*KK3N3g9MeOcf6YV=8J#&*Y7P@7K>e*!b_%~IKuw<4O*M+>F~#|yT;~Q zZ+4B%=qnnVS2Q;NGiYpjGL22oi_qBITS(p=G&c8;r1QTPt94yJu)-~Q>`~{Wy$L#G zJ9_(t=(hNf?Jgm)n#4m=SH9Kl4%|w?ZnLRQCa`m|o?cG5BAypBzw(VS7*~RL9)aqj z_{Y*|E+}MgS>co3%@jQAnh_&vXa(~|V=ITRt(6BFT5+v^V?#%(Z*rx|MxDwgKt=AT zDw}Fo5P|Q(F*a&c?z#C@{+mcUg@R4(oaSvV2f>&FKqf|3O)z0spKGc#n<<=Jyb4)yjr2E82}0?s1LaICq=Eg;XiuqVlpDC)_DA-u~W!!-Gd2 zeE3Ybiw4=Up+~CE9(i!;9JdTm{oJ{H^_hdcXM4{bo>ui7a-~o?ig#Z`u2d>Vv6OO5 z@wuY>Nb?PqKP4J~sGsEpPM5Y*OTF{Vkn{6r0eQ13?Uf|P>?4|N}8#(EDQ?ml?rU=Dq0 z^Ae%Y9O@1q@l6g#(#ky2+?wJ@dYMPCJpV?-ku)>l=!?b8aP+_xaMXL`frBpqN&0+K zEHzL8ddADqot+8-?sReyXO^%%OX~DRt_MBOeHU8fM;|`g`vTz7=fIVxX+L=QT%PG= z0*)OV?0@Lk!DGkr=x>DEzneb$(6M8A^qb-*hkh*drGC)=d0i7B1|j87^RCLL3sOhd z$Sn}I98m`}!!ZX!WxYM~K;(wD?)^%Vl#@vz$O#!G9no4Io)>w8QfkjFbXO;4JlqY` zT?EN!0{n(m?OJwtk^HQ!m18!1S7At6`qSwuH6Bkj{JHV*&XJhuhw!0|%g{7LXbbQ@ zH{aoM=_COp-*xT0okLhu)9Ktz`j0s!bAaCcR&r@B?M6*KBI-<9lBdyoQtKQg4Nhlm z4z+&6qxKMnWDi}WuyYvAqz6)l!%<%BoxSiRjt`;4>N(jae+qlYS~*$XnVzTq?P9Vg zcb>v^Uf$X-#$w+2#-zRO)$42XGv&vVa%hb^G-KpD=~I<0w&7$IDvigF>N`Tc^vO!+ z$)scbXSio>F-(NSi(XKQVTEU(j!{RJu(hqeO%Er-z2L_tNn_`rmhXs%CObds9@LYT z)gfBPKTU20J6+uzKa?gT0HcAD+|HZoe|p2|YFh;Qx}U8+I`7$ZzF2zYaP`XJ>VJmA zRabVn>Ut4}tJ@1??>B4sZA1@}`X64OTV*ge6Ybf1DqHXN->|vcxL_-a{I}gw_200# z+wQtQ`K3{l`CHyyYWgNp=6`N9n$?05HY{6&7#M31|4j)TG=4~T78X9G8&iDe7E2CC zGt+jftjgL^VsjUekfgWAkTp6sIdlw5Rv!X=)TGB9z>gctFc9rk+NX@ScQ)J>-s!q- z25+KS5LgxOtM5(w8!p%(2AT5#0Z$$|jSR&hUYYr0zOs-A)K zKCL@6dR`rVy{5-B`8=?HUvuWF-xF@lf$Q81RpQU9G~zef_q^KweNE4EM1fIT|6I0a zI9VG|cAvEl=a~Al(U_gtrLK6O!mjT7gYDngV~_=G@*xrb0}HiP?3D{L0R@ftHQ-E1 z%p7O>g{oj3o~97i&rh909Zt&u}c15%FjiA3yC*5NUT90x4=97b!%^N z$OYG=7H2@UFG7>8uo;=erzk%JsEZgo=eXjjN_wa+pQ)uO(ph#_hd7>I(qqYH)A1Z6 znT%;!;sA+M))iuc-5~k&q8-Io7rFI8Vs1Kj;mFU?hvp7FYTX>Vm*2hqyBGPIvx+UD zb&I-Iow`_Ec{4e)bj;EkYv@`JB?n?2oM!FKttvrM)FI(Dqu)9@Tg+WFzo&kj(MrH! zOFlznC-tbvMzkfU1A-+IJAh7o0t4u)a0L7vLM0bN#SH{PrssGW)aPmZTit_hA=_WR#xhijV#N6 zuyTpiAa9AsR$D+E?~FZY4UP663+AD?#?rYP%XzT{$ijeY$)P!myf-jJ`TDmK6 zsOsS<9!&CquYCI~$WrmNb^SO&wu_u0VahCc0aMS;%+Gg8;Nncb*Ekcistu;gu1bq! z0!wjB%PH-J5NOtEN^+YJXZDp?gYR$q)9q}fXMfL2p;?D`vp&?>3)n-~&)(UF*-Nz( zHjOs#|HCHHWw8HIbLhQm+FS;_*6Dlo0@uPf${W#DL+6IqtjGU39-NHQ2MKae<{}4T z=GTz`p-@{kDk5>+=|;X`W&!dQxL4rJv@2>Q(3mtA7a}?*+3v*~q*Nkx%sFKuoeA9O zzu(#vA2f+5u09rImj5lxwuG^`e0=J|q7|Gk>!Q7;39rVvy^73{E!6*iu#6!$id2s< z3k{+qo5y*?=5-X0RG5>ZWv+_5haBA^M+q~ljSo*D#4H)a_OU(2M#E9lHkRu`r>0A_ z4beF?PB$@69AaiRX~7NXW!Wbhg^#dLJkREkQpyXKOgC#XZVNVHX3?r1eW{bDO9M|8!1)5sC@V7#P+e$X}l`-_fn~#<_e02sZRGi^R7xy zqR6zV1}Hsv!m?I%EZLNhbO3YCpArt=k3nzC%GTyJ19Pk1Py4Q&czHP6W;DUg3meJo z`m(f5yUj~Mn}P8BwVuIz3)rlWNbb3=B7UVw$gP408dpJj@(-b5l89C-}@=$VU;4XDG0@;Jj6;SF>NhdOKF0PPDE^g>7 z61lj0(n50wlrBST+BmX%O2m)6Cim2SxXDQTC)eTA!JVg4^pF7#JpX8QFH##LU>8^H=;RZ%)#!3PFbKU?G?GM;mPscS1omB7N9a@a($`NE zw;#NYd)3ChDckz;g7%82NIEBljQCz7PYV$n{{^KSaLK@Lx+Xh%Vl4>CrlT&3y~*_I zCTs;sFX#E-(w(yH#_bI?d-wV7P4_f949dl4m$A56KpG9Wdsf5B$%j2?TXS`#wvjWL z#DJHPR^eH+)26gCk2=(74f~gofTdAR!zXOdl>tCnf6O&_lox4Z z&4^5Jz`~N_+-6$$>@bz?h?^+QHd`v2ZeiEDjb29Cze(3|7;K*}T`{-WIMOXM*Avgy z8LBd)!9$IUJv#L6_PGZu8cx+Bb8Xh2@4s7C}t~_C2O-A zOi$u}O0mjf&inyPy{7E~b^pt=1vgUA6?6tyTPCSdY}4gw=a4g+OJ!^b&O+n-UNrOkK)N zZYG&Vo42-UXM6JH2u=sD!Ga^fAy+?>h#S5$)nE=_yhCC?@>Kw%SlKapOEcwd+6*E% zAj>o?XYq&i@M}q1Id_ekr9L*?flnB z0F6gLd&gJl)*Doc*Sbu-ZH+%|VUs1g4uX_HM2pGu(P8IhhU2<%$Lr0dt`*&l+tC$J zp01+?Q}~Owg!}4PH;<8XH2UJ)+lXcNva!r!#E~?=yF{Y2pCO3a;z*j`Un(B1{4j|~ zkcH>xStB8crXEC@@hCb*>y>QQO)Dxy#9hU0)3+lYl2KCK`^?;w zJv!6iK9C0X;&2{6u<4F3uuU!CnX|5v9d}l>(k(Fq_js&##gng|B5&b77xDXnQCv{? zR|;qqFCe$TF}Uceo_hC4z&5Ks4Un$_1XvzIytPSj2Nu&JNv_^sYQHtU1?BHA-PRq8 zBtCn8=}>PX-$t_Df2h=i2QU#$eUV2A|0eC520>mvA^KRyIPtP!c?klHCFG8795%hm z@b{ro>z?Fw%&z6l|46C0v+`;hZx9^S(u{i*0`n=va^ucl{AQ~FPqx#s=I4jMii*YM7(G% z^#kOy7Zw%IY}qtYLux#5o@pcyKR05&VoM}CKX_>PuA#%M*rl6Vc?T$du}jt;QpHK` z6qoHpH^C%QLg->gJ1e_=cV*_hy!tIa{Gs|4LKCN>l`-9fh!6*)mZ;GeE8 za4B_zI&*vlF(%S^STj+k2vxtHe{JU%_<`zuNU`g%ESL``|Ey2_`ua`UYy3i`9CYdj z`f`GE5U-^P!5Nr%YWr{O=ZVImmjZZ(5G44VXpsB*83&+&d-Cy%mRE93U-{?P=3js9 zIyB_pZT?$0N&nJ`sJS=WTc59sO(F@EGzh(Z$@l%bp^zq zonb>G*I2+BE?Nt^uP67w($}PAovg^Fs{2|ObGKqy?4YK`%$-NGMQ&T62B)30q4Z5DcqLz?Yrcr zo}n8Tl^99vgTXW|f9ro8N5P3LKr8kbL=yE2lVjU(ZtfIl8peqDNNLmNJFjEbW`1Y3 zWH}8ed{6RKzoHM=4~2;J0#D$3o;oRtJ-%0FEQcGUF5~l?ouL|b))b*)!rD5gqI;vW z+>30fjSEbIk>Cr9p<&u)aYU9xX#vFmGRJJvE;}>PqWkxAu8h+xJ=om&H7>s6a|W-! z)Wvucj^Q?sBWvurT#SRB)H>NYqMqRWrOynh{F7Ag@SG7G$Py1&a48@OyO>0)7;rxwQoE-uP!=Qx2n2|B}> z)CEsPe`{|gm(;T&lR!b)W=mQ}5!SM3hkTKuq7|iP(7rKwqBc>T7&|`sWM6%#%J1>| z*b`)J8m#tnA^VA;>cH6eQ}x>LiOK4Tu@O>KPgMIx2YEU=S+Dhv_|vwKJr!%O&qA!Mh8Yt4c1174^(NPiiDq3M`|Z) zlYBQhcEGybSg$&Eyn1q|K5&9&`ub}lwaKTf!{fEdQFTT(rUcPpysti48#p!6SFetr zs*jIN3{^F;YNMG&b&>-ixQTnV7JwZCi>cok@k&(uMCe^VgM~CWyK0nNA{}50r zWw*Mb>!)b6J~S|?0cF1iEag?-2#2AG@u7hlzrY81yn*Pc1EJ9gl7%aaci%{Lu6-)!Rlg``!&`6N0ODlooo>Y1r) z0206fw_E7FB5-pndl_msd+o|f9yTAl!1p=IeHF%;2m0_;fF8eubYdHa@aS#R?OrfI zCUX7JlY`9l+wp;+*P!=DDZaq0Agej-gF_Po_1ZXm0)HH`%zle+rI~0#0S+>%FE3Yl&2K&!oq0CjC$Q@Es~)W`%*|(WZ=g7^ zv8i-;>${5|gr>YFhIesldF8^?Jd_1S_dRm;e&EF{T3d2)wS=W<8CHxfAdaT%)-_gH zN>hZvK+>46hdk}X!Hdz6f;mulov zRpFyZu&ijSZ9n6rV`Dc<|^wVTXB{(L}l%#R^3jEYLtSbzF+lPs*OSg~9^~ZA} zXH^6<{4?df5KGLv88~K;;indekInd+pLEYWCP?v8GAn|lKI7|ZG>#i*DUZg8(z>Qs z(SG4f#iYu_8WwHnvpUX+gE74|u9u+XnI*`1H5auWR#SK@+{c&sU~heuw$y1LcS<)X z?z@go8iDF|FgjC*`c4C2lzE|nS9`aw$=(WpbuWDY;zc#zlGdZw5rv>@ae;P@G-{Mr z*HrZ!hla(AKK1KnPihV}zjafZDskg1YR;spa@_x+B(#9qf@-Vz9L!TXv(+d&4=1pId`XavInP_Y(HyJh(%_KRu4)v}COC-2f z3Jpsb_w}vq$-hgYo$p(@#j5fPlBQYmJ)DFs&8;sp!{z#ny>nsx7%guQDJ;+PW^#&r zl5}$62n6Qs+!vOHG=^j!Q=Vx#HgxuMDqXfh-8o0v$~OKH4J)BbpylL`7VScIh_r>T zBhp5;WNaf;HOTiuO0wXX_N?b}b3_VxgTSh1N=4CvbeW3_9NJ0HZ-S5I<2{fjQtRyQ zlnRQ|Yjq0a%aU?+Ya^>Ejlbgf?QA_Wby228&tMN9lH;NB^QIB};k0bdEUZn@rD<4Y zDD}M0QZFK#1*L|arB5tF3Y z)g`9WOnVgi;#QXeWoo?@CDxLFd)f1DGk`kOlVFmA>UMnPT!`LUCvMIPru8q;#25=%$0F z4uQ^ExA+cb>mvQcY1e%Kv@;cf(eGy#ah5|$QC;cS*OrVVNm7lT9tT<1EQxN|^3J;8 z9ilhP=wO?hv|DNbFkD4u6QW7OS#a+u_VSRzF~5WRq)jcbF{$oZQd5|QKeT`ph?g;{ zieq4%sfyA*k^r)QApLV|%en>{Qb7cso0nI-IH{;~aTb*qr<=esB*T!@5k|nMBzi#B zp%LiR@@?kG=`4PP3kzZ;Qh~7M8OpkSON(v72%GZ<9U5IC3^WpXbuTk5a6EOp)B3*Z zMQH}H*^n|rotr|a@n-Z)=MwY8%Jd)2`IyDwtgh9y+d(L{?TByD>VB&(1bouCFe=~g zC~yHqjVNMIN@BWoracouM2rn=HSn@2)7qs*1jj>!Le~<~vR~lo7yW%lq1A79qX-n= z!QFzXZuuw6X$o%ZjTz}NtXxjJyfxV}r1bgy&u^|SPVDWtARjNhF)C88rZBcHm(KoG zp>VBQCY%BK_rSU6D<5!f%uPBXEd&kSFG#<*7#zR+D8sDEO zjqiT}N@Ld~?`^u%s^3{I>F3{YXB_FtONW~}D*suYnxutyxfsY2AbFE@;MoIc!oLn=Xi zTSs!UA0>N$vj@NP)wPv%Id^$cxx5L#b2e$2uxeZt+blz^8SJ;z?RR-kvNfEdLi*cS zEO#ecg9GZGlBMFkDauZGp@AcXdN+pnq=OGc8tjiZw^$SKo2J6 zUT^n7za_0Ryy}!XUzGm;vG*?EbzRqeC(gN-Ab3bo)Rjb0mwH@XJqS_+Ktc~ol;j$G zNsuU#20`m(8E=q?K!5>2k(5TGOzl{9oY+od=Zj;fb{r?otBvfh>F30bC(YDu>bza2 zahvV^yCDKE0P-`Zsb3>A2xswNaL{JN*7hX8M<{NH~j0YBsv zJd%2*$0m#_oSIyzhC#y24F!x~>HvwIW)@F!W=nkpGhA5l+mg4W;@RBXtOYPvzZ~PG z89JT!hQ)1}Yuit*VK;?W-gl-LBT3e`&jVHE#>J-O_beLMgNcY;j zR%XC%|SR&Xutw- z04!sloXpHv6$OP_Ky;~5{krfWq>Muym)r6e^(b@b*ML(yr!OF9)NcqqT0?1iCWDWq zi!1f5?Z2BK6n=~YLhUU=PCXc~3Qs_HLpV(pWB;`IYgA@C5~nN~N2>MUlxTm~c4b{i zg=E298Z#khegDd$Ox{YpOro4d@JYJ6hV1X!j%ve! zT~R*Wvc{UPI3ge9?e=zMovz_+ZqKfKaB3-^(~xIkSZQj_7qhDm;ZT;hU2JbGVAl;f z9yU|8ZbsPz19rkwZELpfG%DGVMchIRL2HJ(^x_!Lwd=FYeq5R-!o?7>ZpfMs>jeO8 zZU?~S^4bGgR!|}%s+z;~5osk-?9G86Dt%D9ExUXUlLI;RfXoL^Z7!GT^-quU9*r z5Nj`H8_J|!+qTj`bS{bvX2s#X2=!3+k1Kb;o{L?V%WD#_B%1(SDHxQ*coL6m@B_KJ$_%Qh1nf`Jgq(G ze(HxfsE7QZ{%m~t#?s4&fB%q|Yx#@hf|uM~uU>Mw5u5dIcI>RV1D@bcq38>V^zv6m z7E&rPcWf>>Ubm6cGc=(?)o zW_yctd38s({fS7rx#L#*6A}8F&=%2jOUI6Id#xAOWc}$^+N~X4I1?9G{pl~S>v&Q< zb>RZ5KmFzP#obwd`pX+Sc3DgA&id0|-Wd7>X#MFg8y#LmW_zvTek=xv^yxOWgL3D29tU^)egZNdD=3!<+US0A7(&ajY?&?g6YknemfyKNDjEYE5^E5w5cC1s1!y1T|Q^y7UrMx8KD+p9V}?GRQ6_j+SJ8#t<|8snW_)^o0Z;v=RMiys#)5J#^J7x=ac%Ut0d%; zWuDNCl>v9n7TZEM<)BJsR1ek*uYE3xSD?BgHhRTHdxs54N7|h*Uy5ohamVNO%^{>X zM!!o-Q%r+^f~RtBoL>i5#KzP5Myuf$71tFM&o)F<+sR)L`Iq~yff93csWrX`gzrS9 z@)$WICr+XwnLo40G`LCS6jbumCwBn4Ajva z&5J785U_&>&wQaEP~!hkXk3?E;y1}_gi6UVZeBwRT)Za&5q65$?&_+E*g8dQcc*)G zh2`(}v9!B?sh!g8!0a z)ls>`xO<<9FD;fa5115mXS@Z4wCa=4)+kwIS18~jskkeg`-Kp@6$qg*Ds>7GnWg*t zD2_SvP}>Uq?`(xa>w`0)JNg)`Iem>b3lT63@j_{gCdx(IKZMGLO|2y^LL}jY2jNmm zibsSHevI0{xo430qG=|_$Y19(b9ExyUccl!!Qz$jydO%BgEmf1WN~`hTn3-JTA{N) z15Z^ST7&|xETdk+nni*UsqR1Pn!oa>KwBErl`bMYD0FYmat`g@6OfaDoJXriB65F04LYeKMjv4Jfx)p)XMWRF3l0QLY!C zUt=i8OY3AhSE+w`O#{7^@>rEmJF$B1g%GH@yUQe(+D=^ zL|UM;UiGtW2&-7#cNrbfIgmxH`>UJJ&weCE{2kr;Ss{%#6rUAV$YC@Y}$}m62 z!eO>hmU8cJGin4yzrB}nbT?C&n8({wVvn6^aJy02LVEWN5chZJke}C1^%Zu|$$SUt zUUM?vK^1n;$$SS@*g-SZ*|>u$VF%f(&=))CRK9~MzJv54h%Iz*K7G!_7O6w zGvPu^S$WskMN@vytT`elBm&lDxsta!={;j=AQP84&UVsD4hTW?B=V&=IEsBzESi|# z*sN;45wOEJem38nmv>#zV{$O$(C`h{Yd+956_OBXVUDyzU*6Jv zvK5B!e8~6~GIX`5#^wB4d3TEiTufBE`1W@1VL{j;?`dRR=#4k^1m1)fHOePAjU3A( z7HnRQEM{+qb4XvJ2^Z*yQ|c~ErzMn<5$x2|m@OFsjx-6}J0iw)=(ytwP;pG_KZh^zS!}DM1#J`&&((#F}QheD^vMu zeBI#yI88Z766{85v`|srOsBeeVAY!itZ4ImvFnQLE3pE0_04iV{trp%eCXk3gtZht zX4>CiTeNk71U(|e?w8?=w%lz|9QE7HJh>HcP1mh5%I-5ub}-99!zH6uqEy6yY9ks! zLOm|b7Y5BSO|KN4f@Gv^W-Mzo-%^Wx&pUkNbTmI59v&prPgGT_^j^yd0MO;P=r6H-s0rU{)GW}D&|UYy5&UEJPaXyM;Zs@Mc%_@Bl4 z8m;MW*q4T>tl*HfRni`GpZ6cG1dR#X$+j=0ih}b;$)6iibaqv@3fJ}fN$dkCbocao zlv7Gv3^WZx+QPtY}JPqtl3#2FT0-LsMnnJ_$V(NsUAG^Hq( zK5SV8wb%8>j?mzh;99;>I~hmC)<@~YcDUTV;Kngbf$id?lR`QG+!-I4-8+-D>*FJ{ zduOuo^6YnPc3dVpzb8pQlvL`!>N_f@%&~8S8nKU+yYLBjS&F{|r-|ccif8)oO{$Ih zgT_7#tzn|kW2!&^t2RM+hklqQ7(^FFhAK<2InpbT6#Yh$LR{c+b4;FyguvqsH)d}^ zF~RQUg#Tbty|w=5?uX<0EP>&yoAKJ{q5vewW2M76Fs}U47IzHXUp8r-P2r=GHo$K~ zfdKP?MNsih(Q0x+R}iT`a>}?(jmTjL+}`;bA$PQIbf576{y2Ub7$TwP;}lFXoC3xs z8A7T6(_+Qhpuq@D95vy~7>wkeOQVmUJ2w<}h3Hi-6M9L#W}q`%1}sIO#jL}4!7bFd z#A;2gpV471A;;#36FWJ-)V)0*54H#u!Bq3v$+BvDv*m*vz?^2P&7zC3Pe z#7Ai6gUQXeWOJOjWZ3*j((%tYaz~AB7u*QVY!(-##+RbEkfYnK57D(p{BxPMx2-L} zttakMEb${r*VgO~=+!cC{)i6UTWxStm@K1Frthohe8^L6@>R?frG5A#@d)!&n?Ir> zY=P;eway<;I{p>Yo4lmywVIJHd|_DZZEGE-D8RW9nOYF(QPMc#LXzG)x97B~FqWZjjaZ*jw)PBveYEwc2L zTIbIs9sfH^PZ4()34N!pM%rzwc@g4nYYl`VZvpf(N!Jb88<<^1YyXKPy`}z8$v-PU z1;jseg;FV9QwNnL^_7*yj$-SV1HS^qCz7jgjE`XD6G`*ttlwbb z$4@2c_4Qj?F|PR_DW6-SMl>s0Mtj9_v+v8ol_Wd1Q!x6Sp3ZO#0tw>uJ(!YMsBBbo|mKPrA)3<6@I;ZyqMS28e!9lOABw zYc%Q4YSMRH`lN$WB}|zvm@<9%lzC);&&Db9$do^;DW7J_owd$iO*;MqQy#yhb#C#$ zxY&eS8;9w30?n@`UDsu=WxAc3?yqaQyDo9MXVG{dvV^(vJ#(c4pDT~_{_AnBJTli` z*IfTV(rl-g*l#B3w)%f^S@zV}xtUY=y+&U_5s?iLuicoqxsss>v76rP)HE@)*v6l6 zsY6XOE=vgTkY3QEm^h&udMW2!@DH^RfZ6lvGU_KJ_FEjR3&hf6=w_v8_er!U*!r+g+0KVi0Y+Xy_`}GAP^LLXD zyguq*SL97(uK9&sFiZG}KS+jgg^G0ft6k<3;7qx3&b!UoXFEB6@_ZFhNHfnivQDfFm&@UKR{VII zywFFFhHG|AU}2Fv#O>&~SNrQSkzLE^hRcNea zY>fF|^6bJaJQr5auG5oe*O3(O0;sscn64f-oYcw@bx6*D&>(4^7Z7}diKM`K%N&7H_?M#sEV~*c{$h6y^WvKFwS{pGg8uU3Eh%Wikz?Yc!_{x@a+`Fif1m=#`1 zIyn03zji(Mjr{0E&McV-PtW5&V{A?LDSU3GPRoCYcd*4VEI~SX8&*FKiPr-1uuLiS zKH6qnpyy=G$1P3f#))~%?&&#KBsd0RGABL>SIkRPv&E>5Mzc_$6KQ(68L5Y(CTuQmTx&(~6`|e%& z#C0d=Z5)~!JDtCh|8R2=6BUZ;rkpQLrzJNgTFFIAXAthRmhK9}F>W&8Ro4u2aAL{a z6MQGKyF_tZF8c56AsM`?;LXu3eW>>$sx=S)Y)MG3_3X2jCg7XG4_9=%1KV9<*REZ= zd+dM1yLRod|2--E-^)KeyZd|Y*gf2T$DX_H<$t|;Xa79e+t`cAl7%E&AM35VY?vZG zKPNbEDdmxS{IPdlf0aFg>CF zt3~h9xuxwgvY-;QJb}un)wnrci5Gc@DHeC{A-Vr4s$ikzjFPQ6ayLiB+J4CD@qj8S+Z#CvIbnrDp?VEzNIRdUj{S0Md}((3GC-U3yj%ywHr6tPvN=33BW0 zhI(3NNXp<CO3OydMQj33)hO@ z+%~-wAw5ps^1JT@Lle&|qJ8M@?)Ep^r*bmWYr0tFS?{D1EzrFFlFaW_7u}C*>ThE_EMgswEzVr%7z!Tx$2-%eRrQ0=?<;-FM%4=bf*)<8HbM zB!r5K{XW$=J~wkN@H#QG_RWZD;Tu^@QmccJ?V!Su(r1gsdhOayRh<$z7olMFBXq@n zZY}j=1R(k^NSy4;s}O)vTsKC2A$vpCKP||kX#2=lUF<}0Q#h^OvXrZT5SL4x*nYJQ z;(t9*?C0LOsk3{}%*>K3qVTs?OS1qBZ7x(E&iQKjG+*-KTE(zL@{ZY*b+c1xQJ&eX}Hg+x}JGJW^LG!E!s zbu@HuFU?$?6tfSFg$i1&IMcgVooQHLTN0hlt+~RN@+B)RRLl{c|0ti#eV!gtYs~NB z^_FSpQTGJm#o(O3VJl%Vaz$>5BHS|ED!BO35o88DMmd09(fQ*;Np|66n{k7AtXZ$U z-h5ti!wWsn{;rUbUqx;tct~Wr1l)0h4%7;q^sQ2NKtWk#;t0DEusaFrGD+XXrKD4)NV>y`A=kGO z1L1Y40xCJTOq%rMzV2}@=XuJOJlWi?1(4qm+diu2+ek@L%UH`$#4Rvd97g#-O{S9s zYe{{*8nh%>eH+q@hMAFt%90Eha7gSW?I|3{#I=LSgSodvvwzp_*XVTEeb?}=-FxoX zwP*KTy}NdUJ{QY5Wb_=Di--#Opju0tGj1ul+A&;ISjeOg`)0UI=x$fZBU%{yEtDm`Qh2 zb3Mn8^`T)|?0al#ysrSIZ)nOg-AqjNJvci*J~lgY#L{am_6eZA(jag!w8JOoAp^L9 za~kQ!#bxCrgI5$^h;Vx2A2@b-t}e`*X61CjG(@bKvZy>on8YYtV_JQTmSzOhy{Ekj zf+W>`vN~C9j6NIeHahnJI+?+BHWADpm=4cE9k4=O@SP%)_$q)F}8Dl7<-q5`r(<#P!I5 z^K`dYu?jhRSq*S&|9<|LH7wjMPmtx` z%D6T`4lG@IxE_WoAGX!_(oSwOe3bAHg}O;cwuG1DEO17q@y?_%RNQa_ zt5WaUa+-~5ml7UWNLiWP8JCG!d2ZbcU5m1n?nO_+xX8G)$judS-6v3%5a5fMbp`!9 zk}mfn0eF=5?~or!@Ui9B@0QILAKSz8b3JoJv)Vm4a$&noL(qO}O?fez^CZ@hA8pu^Q{J14RtRF)u*6_=vB=`CI zWaNo(7bcass{#P4W#wspF3r{-0HMJ^T&rhm;s1&W^@JrPwuvu_yg8|5Y`9?FoCmV5 zMa2Y?@7q$%Z0yeyJhU%X@3GKuDF38Jf*Y^3YdLz>4TY!LP1y!JNJql2O3AZsXuZ9A z2qXX0LTy`?1(!YCytk}XgS}n<=Xd_vZ*`HiZD?KiZE&*onrxHzRcfwW6s6`5B|{sn zO+e4!nupa{82@uNXE; zQ|w-0ik?TPZCcI6>>5FQK#9Zlv(2bh9_C!znbo`q^oS?*8j(vyNN2OjfAKGdc@L3X zVRhYG8mHt8S~qmL{ZO=Rez1~lSw3pO*+h0(%dj@$`u^9(d>_lmXtkbtk8#e-PWiY) z8_E#ZX0uJP3Vi_BEu8E72VVI&j}odmgGafKv>4`Fyr>Un8_KZM_Qyn2No*yWs}4*ZH~vGSav&4*d( zIEl8gTKiIRsf+aWeMxrNfpe!3@gj+?zQ4L7CRXKHG1J$+Y!kv7MK?y|i!>qu!Z_FZ z{tM)P+UTD=#upNSn)6vr39Tku!Mna~`|quMc_1x#z~3ip*ZFKqX~08B0TbsVRxUE^ zjoEsfwnkuO&}}sAXS^EnHy2A7#u7hSZ_*lN@*;bb8-W(|*3}8n&L00#%-R21 zyyT=|ec3fDz#!L6xhxRmWUdV2KK{`B$uzsM^o3(gN`)z?Da>Fl+b}kJ`s5h$1`bt| zVG<9oI*E()*E>+^>;RQM&kwcqf2otLe`|KdvaV{IvI@1E13%WEwS(olz3cmTT?*WB z?!sKC^t&g$Cu#m=lC2kYN1A#~)`bzpcZYBMdh9+5AHCWMCellIptYWBJy~UGX*Q(X zTYX3IiP~L?tdYc>JAl`Uht7r#yE?h~RD78^+~aq9*JKp{EuZX7qVdYDS3kp>2fSr; zORL@WN^q28sQJrC4SO-XJri;Lx@=?I5FAdkW4_22V^m7r)KR-ETUR_L zq$24&K18+9;Z136L)Jy5K9NJXr|JY?&RWd;BJ(cjsEvwEz?E;$Xt5b`&@@Y0d zm3lh7X07EWvS*5}$i4O*%9Z#1X^rHME}K$WJN|X~^Wi#xM568r|K<}LWJ{~?UF&*&eC#=!&&_SWT>1RBo;lYJ;|G&$lQ3GAF>9+cr}n0C zxh^2gv~?bNTJttrxkhtq+sa8G>6vtCmnE!yN0N2=$z5BW_*;(lOC_E@gW%fcRc#QM z6l0nDE(;fgol}BpS5kW}Tf5IQp47gnblfmd>P=;JEH2c0LUt8k=}u}CAKJ(D|C>5+ zcfzFJ$#GITEo-;0xz#5w8mk--eU8-p?PiVJWm(mnU?%RNp?kPC>IB6tJB!B zw%-_VI}A8a>R4KY5^xTQK>S$JBIA@LmRE+qdoBfkK92ndB2T+O*`v7%K!}a*@5fY&T2ck^Yi%GY>k~nwbeO&`P{9qzV}-W zwB`*4)t2U!tyme?84g(W=4S^snj_6gazgBR&7F7O`yHSE?ay7l{@L9l{k!__+;!)! zd-i^7wsoS&VcCAtQX1>da!z*3Jc)W~vF`-`p6H3~`!GbHZ0UI8|d|~m` z>I>KqtZIgN7|Gu?&sOlwNK6^hQEn>IQC<;JOp?)}=5^4CK_p3~=b$7V%T?~zM%*Gv zDlPXT0o^32^wgDWm88;BSKP@M4Yu`Q7B{y5904Jh zrYyQ~(B8B^dszA9D*yUtf8xIZ5ijcZg8L~e7bA{U;`n1Trx8$}jYVjA?A7CGDr@)c zzT*zEfIc46FYZnstJEL%3HZ`r|02P~c}I@w`_ z5yG8QU?6o=By|f%XYjgkU)P5&s!l(}gnx)p=UGTW2 zJaAw>Sm`t*eh$_tTp^SUm0=&w6v2_9l_YH@A6Shh8!W279mah5vD8&YI^%+i{f=DI z8=P%g3+I@tEx7Z+o>s=&O7Y6zce2yU zt_WtPeDbn-n6ip`oV@k+_yht@?z|@;K&eJb*~nr(zfv|bT2$t%_hl%sm0&U?^y5wa ztzhKH{v+L-$&=X3=C|(&#dw(#hyo47@{Rhs?rA*L3>bnkoK%`m~+Vlpvl0-!SO;S;_#j>c8(Rg_Zh@@}m7#>q^-Q zgqxxv+ZV@I4Iq`q=`nfIXf1sqba0Y-oujj@wu>mZpaJXIce#CR*=Z-(*PKw6zR>BH zKH04tgCYa=d>FHZnsRRDStKvG)?_EBoawwQtfyp>GaIjpPptfzs~ho&wLWwEYrO%&s7W#!+O z+z?lOEi3=NJrJhb#dLotA#+kB^sX@7@Y0c@R{ty^pOKjVS~gQxm0alY z)yEwr>uQ}ZC+Savl7F@WN=!r4=oV(SUlcXarQ(GO+!#IQcPjabN_Kr^7_)mIdrzrL zIZ~%2?>kP`fw7m9PRn7(a*hY_F?B(R)e3z{N+C>c7k}wk}{SynKC@ zt|2^)tV5q7JdGNJTwmQO2w|6GA$FtI$$-7k-?+A%~XZ(@EEr*+w~U zDhJ|clJu98idI0+{QQ}uYg6``=-c^=q-m>fH^jtwK_QG1?)ZKT1kH+*ZAjwDmxggY z((NxM>y0M#$nyMRa`ooyE*pg(e@Tf6x7jELZ4j|_kvNNAuonpQ%R)YelECm?Ogt#! z`K2Q9pwcn?k`fQzV`H%7zos-^J8X=c>@Q&|+%fcNoQmk~*OK*~(F?j`m|s&yuW=iO zr_ae5cDQkb=trrH!a?H~%i!d!#f;m`2ml^wVpd)+Fp85Rw?JI^yb+5vh^L`&;{IIB zjK-sZfJdtXgkY>hIsc#lA)#uJ2#``;{bsT*t_xBrk6W(Iuwt?HNTpv$(k~`e<)NG> zyX1t}3pWenI^pP5rCw9L*sZuX>RG}K!hO5pNPTzq-*H!5m^DB_&k+iVmS2dO*BBNk zzMysD)DRRL5no8Qd=bLGGFxvie)*68`a48J|1qiV2(Thbekn1n(|B})fIq02${-tEw@8qC&c16(tvq0YiPa|m}IgkD;JZ)!S zX>Ntfc~6<070k;xgm6I0o~vwglC7{-{R#zTD>m;95Y-~x;{*TwQJ*+rCmi)IO?eO^pbhb9ZxSw&K=J#>**!`Tuk190>r;g((cuP z%9WFUKcJ*rW1tA5yy^csZeP+#8W<`jY1t-4hJT&hwhcA2<$U~`q~q;rQon!Yjrj^z zL<|2nNms*;@(N|hI{z+7|F_hSa-RA5@2JVg&z)5swUfUst=<9~S?ka29$s8qyx@y( zOY1ilF97}9QW7&tSg0^w=bO{?+w&1L(Kn~rwP6I~6>mwa+rsxeGXgKJD_-!$Thi;B z#S2DwOA2p8Z1Z%KFQw^ChB?wi@;Q$i<0BuxlwN*aeB{%Y(i^1^(x?3Rwlv)qeiUcm z(K)K;gM3>WI4X~P`Zgcc@lhu1q&a-*tOk|@@y-HaS+hl77LEbBWoyu{^C})0^n25A z4DiTgzBlCRq&9993fwZ>|@j9)dq4`kS@nfu>i`Vhq5m)Uf>W<*K+`4p98hj}2 zs%N(Xx8>CPaGJihevP3G&?H2$NUn1WOW`TuXy;4eDd9dGm%>xReOOB&GUKs}t9W|# z1KFmm%N{?#Re?8~@6R5vK>^{1Q!?)M*`Qn=$61#`cNEV8SMC_!Syz2&)p?w0vY$y)7c6*UE89mIJvh#>g4FekrsmbMH?fHJ^>i!(fe zqhCq4-CD{j}%2+ST`1OlX2CY~inmJ|gXkP`&;E^tWU6ipC%Gglr{CwK+ z6)3|q#g~uV$D|lpP=agJPbpcRzaMNkVDp=;U1eb-{8%G|I&z7~3 zpG9Np)afOq01gU__A&A~O7H?Mm(76^sK1&uwIS5x#bw*&HJBCoGWK);^v4TtWN5qe+>^cNtbFKZ`*DCO$h1E81JI{z%~__j(C&ZP3*HAmpq&3idr{h6SA z2q-TXlz)+?y>$r-n73N3U0Qc}3A6glIx5g5aE;}Z7jR2YfJ|2|;q%Bif01q_yathg zM?n6IbZ3ukrpv`M{whuXE^H>AY5iCEX1ZKd`v3fYZZiQEa|ABmOgtKxVKec_9RD9} zCS4sb7en~lw0c9hIkJ#~jbv(Ddt9ct!z+zfFnaaXf27 z|E=zBy^zKx6cd#W9H{FO#kGEcTZo2Npp8xR_2vq9-w`ITNwo3S3R~;-ty@dVdR>I& zPl|&jyfsuj3&sv-<%pt~sg=A@I(sVzbp|7|3h{)gFaX<;5qvxH$nbBigj+C=Oy#YW zE3eAaExcZUdAH&YFThzmGUiwDcau(2n&)jS)~=C86OpSsx0OsX2h_dzI8+E^yc8q)a+#Kb=g{2($f6G zd5b69*q?js17q*<(R&~A)GVC2!`hlU69U()71 z*%}+Hc6D~evEe89sE3VLF~;iFZRr4HMW4&BqE+TB=4!^K^>7=dTsgKP_?+_gG#orzCUkO z#$yi6&=s-c{MDYh?8^8Ouf=H-R_Etx*TwLb(r~j=akL-kV%667-w+#>M=R)bD4)mv zyyHD@w0sXXyV{NM`+Sf`-MU&DN3*)vILaVlJ?@>$HkKkl0Bi4ML*cihA$j^h*ny?w z=`qqHcn0&?qLTOYjpY`-#rsNs|5cKFIIYT<{_yt`E?Zl(vE%U|4i1_s#`m5OtPo4 zbS*I5kltHAO07$dRE|#fCNk1ncQyU=C3k&`@dFU4+ftUeX@V$Ob^e(Gt?S={;8 zs@VM2wKx0UI7Z%(-r#=&;0-t8o3A#wNZxSgJ-{uvZtA!-$zA|1THKQEuPC!`Rkp3Y)gVAPW2_tfZy?*z za3~SWDm!lP%f2id2*EpV?D!1E$Ioq$tC2;&AS*=)MYkW5uYIX?l(CW|5pzylfDlQg zl{BIavpba4#7V>pk*ZrflEthMiQ>oRwY*?Hn8B(mUA{tzq&A&7L2Y5#GxAcgXi?=X z$buSpWOG}j3fd`BzUh`4Uz-WjztrofX)JDKJ~zoqnp?<;yoW#aPn^Q=Jkf(ir5+O1 z4$5cIG?aFwj}49NTG8N8;V$I=@a_Jo3GA-4S_UYJBzuWiOe#9zpInrNgctgrr;NLeQ*_ho`a4e*7IjhFY9IAoM7@wMKtV<-L%vuY8W0V zN_6_n_#*D|e!%J!rJDJvKEqEaFQjP(G^>4#yMI3X^#b__K_<0@?Y}SNU%e1=7*m+Y z?g&H6$?S=-Q#i32HMnd)J3s#n`om|Y;(|rs7xy^6dtM3LuLx={A1o~r_|AtVMu4R3 zr?~1Xu~Ec>RwR}$<_bG8h7nooe4Yyx?q9P?4xRx-^F51R+=+n+OT@?5;l;?9zge+^e^AQX#%wQygg`XL**f8;HCl!xD)L6ik9aOVpXXZGNbYe-9a?%bV z%zl$zP=`r|)+C*j$;Pt`%j$)1at;cb9mc-Ccm}j7To`_v)Efpn&)!PPN7(X7uooYZqs3McIcBCl_G#+aU89B z;r1gIlOOSDOT=fG#Ax|J$EUP>bJzm$swG-dVOQ!_Q|AB6cx5lvySNbOl$hO?;#spr zWBa6$6IzD0J0+mQ4`z5b)o=?T3+{Pf5rVtILRdiD#&B9t0>a zN7yFm7BKpdUd>DU5t?yu;0wU5!Lvr+Qv*Fuj`ckE^i%wcKX>)q`}FO7WRG5ows(y9 zlqs>axu|2$5RRnG#c+!}*ht)v*}AD-lF!kxMR@!^HR?XD5B4E_+w=Bb!&|J4nmZp5 z$`?bIxP2;En2jObvEW`2%j_WPP(TjSMsp0H;AOd8!OJ78n-UTD-)CBKV`EwYadP7bX}dXZwqb^Aj_0P(tsxbhd61c%m*)Ho^Uek8%G& zV|FfDn5KzPZ|l`DHn)xV#XJiIJqN|L^~1m?^U;ljO6$3J9@Y4{n2UaF7Oj5BZ>$Qi zxI7H+5MzgP(KfTZhf_nVwcfZUQ_k`h0fJ`cPtB<0V({Ssaop+8oD$y5yxUZJ9c{jK z?cp6Ck}vl!R}E}t@lh3;|G8=#+?Om|=6H-73rO1UU|iydMIR;yEah7!Y5_`;p~YB| zg-+QIm|?_;lRMpLu3=Y}1@kCQS<*Uu9l?pURhVZ^5^%gF1*GmlrDl! zdvYLvoYnf`F2#&j|{y7&Z++gPW*<_m_Nkkg(Uv&6$ z1fC+%fF1Xu2b6tW7}yr%dx_KEmY;X6-?Q=aHhsC0Wt&|=#9fNMRap*BqYp?haAq?0 zb82i3Sz@7m<>SCAgR?ENxX7<8w%)?B11lQ!*~Zubruxi1i;aCl9=+jZ6cjM@Os=o$ zotgJy7E5D`&tQz92FT)KPw{(?%rg@RVe_ZRcH>IE#r78@dx`d}#Xk0Flqi|EnJa~~ zQ*vdIGXiOXCL6k-7%C-x%}y=B$@1Qn(g#izgPRIxtGgpJQX~~?9GQ`v(LYgyc2yyW zPpDYIUpo(_@z0AHea$atfzfmSA?PsTElPp^V=>n_<^-1?s?D6-Mk9Jwp_8Mo;Tv`F zCL&6~Ud%lrO8)gfpR9{JN5Nh{ubuNR9Z_tvPbcYh^&d_eW|_6?T=!xO_O) zd666?y+{G;M^EWm*K!cg>!xEgz}Yh9=~9%|f%~8>wjaQ)_e5PK{oF6z)m64YI$8E; zeljUY46x&rJ8c&0-P_1>27EfX!eXa6Pdl0Nr;}^9W-}<>apC%GB8y`EDeiAjFlRt0 zmcz#78ejwErz#!;ZgvU2<9-I)JuH_CxD3tN8p*5A>E=#S(XYw>>+tKU-pFH%&LZa=!w zh?8MjleYt#&BCs={y|HyjFhCi3-~9mS?TW24aj&-q<>U6Lii{d&JffidsMed;4!tR zi;-#DwYKuc%@JnztmQ&mM7~mXA9Ce6A*#_sznxxvSO|9aDmy+ul*jeaF8+FydOdRT>qx!1N78pZkY}jk+%~&fD9Cb()75iSEw5#NQ?|}LOdh3; z(!c9E=_%+*|85VfSFF!Jg#RzilX&w|E7luB5mc|JV*L-^=N0S!3@?mVE7reSvHsPH z^-8|8fG$dvq~}jbmB5j;I6u8a=_$hFg408;1E*FW`m(bmOGE2hx)tb@8pgq{aqP&! z;l~Ds4m9}t=+Kcj4DLU$zp^pMw30&DLl|%l@8|8|;i193 z$MMZOM$W#0V|?1QUj`08(KztnJ&Go2KdIdamt@%G-!+aLY&?2kXx~G0Gq86M#nTfu;K9M+!y4@1 zks%K3#?gTxvfLlXg|Bh+_z-1`4>UBh{e#DF>!V`se(p1e8MATV4P?e|9D4{C!q$nt zTCx7siuJ7(>vu+9s+;pV^tTjs==G;NSlt>Ntnkm$pZ@Z;4$fNKyYRZwpZ;=NQSe@W z`pfRZ5lnx6Oi?j7ssC}(!O>U$p`DG<{Nx=)}=jtaPK(Z3Ec}F3H!DYc0%UwFt5m(2b2ER#QlF zd^D*1OvNfmF3Mjd0j2?;)3NKhMko0wz?=WdC%KE3x9%Oc8ss+rh9n4P4Sc3s;d4Afw<%7XFqs+Uin+$ZIu(a@@|V+WndFo``FXgz1@CbcQ||ErU#JV9OMf>RR6OILL9O4#<+) zsjzSQ1;^0c+c*ev@+zz7w{2OOMz{vara`>g89E59Eavt!ap{b2H}GW;quO+vMQ#MZ z=_xAY#u|GX{r&N2y!fHfnB=G3@s~#9oLa`m7vdl1)#wg?3NN4A)3`@Ro?l}W<6{v^ zGQCA?-$K zImbN)w?tCiZD&V1jNic2!?bke9S}e8+`hJyLcZn|4Q3&cqFHari%8L1vN0F2+VaWM z1;DJtcm>fT%K9;J3 zO&op|mT@(wN83S%^CZHNYls`zt>^Uy@qGHDJf8a;k;~(Vm_9a7Ur7o@CZ_% zbQHj|B%Wl_)W5}e1B=oQ2V>YL-TJ8<#km^*8i4>X{HM18vZb(+1DvY$YLuzzX&4)P zY2|74#reT93w16zaznvUJK?0N5#26hvB#Z-ABi{@qaAQMjF?}>=Gh3r%L4<=$r%*# zfo@%O3o(r?Fkj{!L9^rN#JqSuD<@3aupo0dFy0o>Y2#d&yo^ebK%2mEf^s;FCkLVc zNuG*R1SkxW!F5V5hx*tSR7uH~=F#SA4Q>DC&@p&O1FWSW1%dlu0jItWum%u(O>|aZ z(!+JcO?m}*?9%*vcixG^LUG6lyqtk7=SszN#9Pg8p!J9)K>+z#!*C)wEwuJ>?h_-B zr_Mp@!gl)zPD8#v`RbICkAt~o-^gD|{33W41ZrK*C8d#qOOCd)$+ly+nBr3 z;+V*mk)f>wejpJaeqMo%Q&W(i2*R0LfsGO*Ih$z51@zx?n1__qfD~E=J`;t-(#h0% z47Z-bD;>fUB;eltbUcLFcMxr{^mTVn<94;UpZGc+0!s5@;tE zR!T&P>CJXspkF`o7-qSQ6Z#4b!&C~kh`jueYzJ1Ay&azXwD)s2GAoJ+1dNPDNlLV= zlp(ke2L2cu8y~dU6}^?9rU?83#}xKYgrTBapODTdSuMuJyd%`>5gAg3Z z#||8Wf}`fl+*wM2SQ`6qMC-;9*djieA-KaWGG?6R=a8tFj>l%tj-8JOAJrtvlAaOA zS zLqnA1Uiku=D7LbwvjU^imJXI`kN}rIIj`f_uA+ip(i2m>`DUf{Q&k4PwYt61{JJE$ z(qfp#_AD4|Z$+XlB+nq$An!?kP$EvblG)x5d;RFZ@Ver!b>{Kr2wn{L;)jnNIovp)Y9d-$cE~}6FE<`V zn2^9WIA<4Ykx>a&NX>5A;0QW~!uS?%-(Yq;E4mK%8k7axY^PK*M^c;J{pI31#>G|x zu`T2v!Ms8~ES&44VBlT|D>hPIn(s5GW_chk^i0rvRv!smYsIu#mOz9e&2wYo^%O7) zt7Sy!7hZi-kdQ)xj570kaQyA)!aVzNs<`|fXYUA)3$jiH!%?Gg^dxqe#%cRECd1sI z)Z!~-pXS%=fTPJ7GRKXbH+R;SF2nDb!P)PNGT!FB+G@Z{wNuNhp_LsC5aa6#GqM;R zRz@x@QJOH;n}ZS6PMT708JOHW7F*ct!du;VbBfT`F!u`U*`(}nJ$14$&K^h42UcSg zVC8WSv!pxQhiSb|=%_t1Hx;#?vZ^ ztuv?6YTD?0>V9v^utoFy5o7e97M`Q(`cIRPVavUz|1_y@&5hCDwkNyIT|D}j^;s=P zUh$C=3m&<2KA5Dh39cZqU2mwdTE8xIASbZs5g^WLET4`lB_sXo^CU%UtZ#(KCqtH75m704QuCgyeN{8|{YH)XUl}CPzu(R_mySQZ?jk_MI3|;BJ z!Z3;-`EF0&*9LZG*X1zoI#+L~<8A%IV+{`11#&a65D=zBM28%9ci?_Hm*8;Kz9 zy(YVQWF>HvC1js1gnADCCAHmIRejr{my&qoKn23@wQsCx^WkjcgHuc8PDoT(P|n_4 z{@cI}7oL{L$G&L38MoErrj081_sW5)-IvpdXy52`B^o)X^H1D$D0A}A-_1v}D=4&% z&a4c?H$JJu*(N#jsI%zDQ`?%Y%X2{*veyiC>BX^`=cbe=$9}XLH8CxV-VD!^%CLDl zyQ0*en^tOfWNXf706J4blsx^)$}8t>+0K{Gq2V7{Hri!+eKd~P{~euK*I;0YwLeX= ztRS4)j^L5oyKJPQQJ}7(9`LfZLQeC2iIv{Hvbiy5#5O0Y?tXFLI{n!qckQ${#%I1b z@TLp>>@As&{}J~_=)j`1TKB5|Qrc6s^V!-!<+W|A&bW0STx_~tzx>+THTi6x*S2}U z=1g(+FAmtIsIe)sVpCiI;YFiMM0luI-G5yHfuXSlj6Jr^Yv;18*c2B4qG%L>*c|Z{ z&z#-^O2!xJw_m&CV)K74TbI*&ZF}r&842ZW;<&3*W~r%fpXO$xyiK(>%Bx?otl0Da zh}zD-((TE8eg?O)S8F@>^!M&U06so9tLxrER7B{aECb$zMRv`Oos~Xq?8L$pVm0?a zBwe``ah)Y@A^0DmNP#haoG$ zhmN2>DBOnROoZ3b{=wnFBZSc53?xsZM+Oh?-`NORMnd$WK$H-V;TiQKZv7^5$KiEL z6*##ziaL@f&cMbH^N`T3+8U;!5R`$8uL#CjD)YIreL;*;d zv)d{+R~sFNllpZS!b0koD4a*-9Fro5-|7H2$S-PtlRxI>mO8*Z{X^CPzA@J8y)Esn z)URmx*{5rlG1R=!F44ZXb#77?0LpGD(E7G3n(+ykZ|m8uyN!P1ZnLerBbK6!Wq0jW z_?nfuz4|aU5L9)vqxycbMB0m@gPql$8KqtizjGn7H&jdE4Ntq%yDL;n8M0zw&j#z+ zan4ycjf(c%;&NtT1}yuyNVt>^j>R>#{<}9`7k^_8ySG`IdX2yw`m1-wIV4_1%wL7R zn8RJw{xFBc=b#skPon$oO*N_`sQbAU#;A?^ zeaHEvzK%^9=sTv-cs-T4?P5<}tfBOH)vxMne}Ihc_Sh5d`IX0s?#R<@7U_)wR%5ro z>T%Ju?-JyCVjhnZ1Q4Ep{BdFcT!Fw(Po?`pYS;2rb;W*hU#EHOSA_i(^`^XEB26n# zkp&?jw>R5 z(>gA3Han5+o35zEC&qo#mG^~lQy=$DSMAB}H#|bKW9c}TUsHSKSNR62Jy-o`3u}ce zICH|Td#VTQLlHMv86#$b%wz!=+MC6SqM1u(`tcLy*k4#xP}T~_h}TB=p2 z(&_&CT?U4tKT#!J3>v?170{>%?Nknph;=H5M&vn_Lqm;)%5)A*)uEXN8m9q}JCj}; zXh5fBX$d3-oW~<1Y*D60Iar!Uln@YBnISmJQ9?XeW#)>j;uAp3T(gB#u~ohU+S#-j zl4tu(p?x4}5prY`hQ$YQ97=UnX1yA(`eK|}ug0q<#+hy0l&R<>k85j{h4jYyk9%}p zyt|agVvGyraUY1;uY;l-smAil&P+C9ZwMdyr(C(fg!MZ{+|r9j5AyaItQ=)!rQ{)H zc~GU05cv|4v^)AJGz#c(%4?bOLOx~X%3G*e0dCEaDKA`qL-wD1%B=6XbbI|*6U;1< z=G@Fxlvid!TU0Af{?Yc#{46gBrZ&r@a}o3mvqj>kQR13LK}A|0sVvpi3h2?sDt`qc z#>qPp1AqdyQ0q>Q&5~`!%RM++C^gFTB3imY%enQ&l|ck)(<|pT-4ZB{N~V=_+q%gw ztYEw~FLZnx&b33f$t3n_mql%Ogxs}8%P-^c`u@h^RxZC)4leCLac{A|7l^=XLUqJe zQ3E>NRKMB=GY*0b?F=N4G;P=eFQ%OaEKhv@;@b7`3D94p<|YXRIccb^+(A{m`jNjM z?BRZ00$fLpB$>A)U7IOc=Ox8D-K*l^G}!+GS~5bh~z`@W>(gMWYA7aEQ>+_Oii zvkdM3v35ck}}b^Mn}5Pd++>I3)of7zaWx!sGSQenf^TQ4)_((vK(bmT+)}U+M5;$tEu~;3eTcrfRWY z(Rxv%tycYbLUEw~kZ@)3+V4(kc(V1n+ywf6jb%4DMfFiErO!N+$h}Um#cZ%)=4Ar-y&l^}J#JsD852y0 zKa*tZ4yf|yAZZAcjGz0);{05&AciNspPa`yI2SA%;i>kIvMwmriiTh|lo8|RsOx3$ z-n`@9M?tKEVwGo;){oehQ8jv-9D6`g_3uEV-4`u82PmP~BVI5Jt6JNlI zXRyE_B~Qhuj(8KDx6 z%B_3fV8zJ{yyB}m^UQxxsRo=G6sZ%C6d!AiY<(&9WdN-Fs`+zCcI8n-a;2#j5+aa; zD*%}*?FHltAFTrGQ)O6JDK!z{Pi2W6S`Ge+{n`Tmk78BXJ2n}%aqVcf$!+BYt^$T{ zEn~R&!mA$SxE#9NKF^;Q>knlc&Agbu67^Z5fNX!b1XLf%)(0?+s4x$Pb8lp3GW4}B zycwLV-IQ(6*~gu11aI}RxOU;)eqJ@-4P|igHWS9QF>qJXLApg-L-b9G^_(VzZubFkN-uhF0W@|vQa zgZ}iFTZ+hH{YeH(#S2&aJ03~uA76vU-JRPdZQ;pkna7dD^uQ*-3}%Tc(KMZzkX~j| z7flmV(0mu1wN8vX8DJ^JkwEuwHko08ij9XsFEr$`n$j2HWM z_utXPv>5+s8uOl*vNkKuBDQUDgk&=G?(u^$5tT3;LMvCqhoPet3rOHABH22!F+!NK zVR4Mi4Vd@kHjISr8Y9$%$4=uPH$~iU9vy+4tnj82$PNw@U8w*D>qs`WiDyVcp88C~&@|ne+3CV0@v%B#H=|PTN>d(h4 zkQ}WZ{ah43p(I3DCu)^@$gcO#V-6xoz?xG|%TiV{RsN?^9~LXJ6vJG!G;ZERP_WHl z6)3nX>&m)(U-UK(*!FPhq(>Ajq(bJ}VLQf9j3YT-?n>dSj6@Q=1&-~LnA)h&Rx2HOdvdat~SSe$>+#^4sgc^Y?p# zFftfn_@DLq5rOs!3rO6(XrN~2=T6wPBWH1x*v`iI-VxQAM}VAy^w8boE8 zmieANON@t7O)HRv0#1r`2pVfcGHc` z#26T%M~gVm3u|j(3~1U|sS~sF<2Ic@5+RmqIgz#X>Jju0&d)1C0d}WNdy!G0=61%H zFRH9;uge!zYUbDFiz+MI>sZv^_C>{x_HcT0{Z}fDfg%BYKHHq_H^#=rDePwMIEF<% zGNnKqw^BH<_7&-%dq$q_lYfMCkme!bP9b;SStfHiU(Zg>ome_)am66peBP$d8$sz{ zIzwe1QVr+o9vwL6Ch#z!JL}dL1bmCki*02`5&84-z*sJ$sxGZLgm7A-jSoUjc_;={ zq!?wXxya?+jBN9e&UJAp@<#Usp}+Y8>Mox+)8j7cStG_4VSR019?e}nLm&D!gd&Eh zCZCX>#JPH|;M?HfZ+f85gHqtkG3kQ+yA?8Bo*X_Kk1fz8Te zgJX!8HWKl@5t^?v84NnVi14!|Q0E!l_`rm{O9@8*`XJy`vs*+1DNGY5 z6!2S`k!^+Lld||f)Bc}W7*lEhxGON}zydBoV>%XqSUNj}5TCQ0y z;6*hS^~k8j&YYsekWQl5gXKE0XhjCI5*Ms<{)IIoEr4`3kkV-@MWNPO0c*|zM6=kF z9Pf{Fx|><-jp^<6M^;=KmYOhknZ9+v>!fL!R?bE&1Sry~AAN32dn4swbr8BS?TuS; zxA!M@#~Z2J+|TB~CuX!`I;r1Q+8d<|pp())sgjG4aF~Pk+9-2)ggIcQ!j_-jQh%)} z{!J5wk(1owNWG5xASIbh8@RWUX$R7 zNsKpd&K@)%_-Tscdrz6sx56Isn8r}pJho7Wv6<|=Tb(Xb;dG(8tNIP63r`F=#p&`l z6%bdcty%2A&%XX&D<#ws`2kUUtJG{91r%opyhPit#E-=z3Gs#a2^A9yHiwFw_eXuW zqz9ob2=ee>xT2IXVApw(@4AqAf2>i~*o8}t-&-huNk2k-=nD?4fON4G?U^ElX^<^_ z3J#lb9i`)r04kM*iJ-2FE`cbzSB}bX?+)AKF z$Q92s8af}rIY%=0Bng<$=&0nW)u z!##qJ<3g;8%VO9Aa>ZJtj`Me#6_c`tYo1Ntl2kBb4&+uZ3ygw2o5N@fxYjg57^0AO zn=1(0PizKu0`YdnZ9+B^f3tj9eDhZ-+9}UwS7xYuJF7fuk3Lturv45$F9jv1LU#+H z*86Ow*)qwJI>6cV%;`P%&zvqhB>DT-Hg)pFOXr^ZUEou2aa`{}daU1TmFZpuVhlL8 z+;i2^GtfV`zE=FswtMdC&DpP{VKyA-Z%(RP>z_qnJ=18i-45v}a1 zRsK@4{wlLFxr4w<$<;T;M+SQ-fwO-tfz4uOe^=7+!|>VPPD;a_l_10o5d65kV9}G2 zx#ZS{E)z*vb9A0jw2SrV;Ji9HElIjoXc+%zt27bu3q_10Ss+uzA{&%&;45dpW?IyD zTu7RUo*FBc!Fzw7Wr{IH6j0bMX@}Mv_z&j8*N~KFTJqYz(VsD z%=h~fc<3kMe67+6JQP2`Re5O3I)&M?2Ln6zE7Pic)Pe<+xrE|9;>qHy=M07F$*Ho8 zIe1#Wx^WZfMmt7{gww=Rlo!~mqm(8rgZzh*z_GNzTmX3i$HF6d4zOE-)@WbjHOajO!zjaq-BgABl{MN5=e!7}xXgEj(g=Ea~`<@U2s&F^eI@ z77!8b;$tib@4KMN^ZS&M$24iil&8XUnvjQ8EkXx9K~O!(vAB{3ajg*l#Yp5W^J7U@ zEqj#NuMs1`Q{y*bBoACVBN^x92)()|0t9ECAI3#~BFVO7|8^Z*gzm*fej}+~UH@0| z;I`mw+aTOtNH4+4$7BiN%#7WR&recDXqa8)8jzT01<7Yom;I3QWpaM0r$}It>oXUE z>L6-W7zF_XRWFJ(0+~s-9umRmG}y;EN<$BT$@2|FopAJebZ17|O3^>$`i4Tg9$Oty zC^8BqWN*sMMpb#k8Q-wt^h+=CNq^$#fsx~fj~zX*Z}6ZJ0zc5$bzkvSgY3eO9%#ux zAwB(LM}{6L<(|+hr6Y*{6n?bav0%jRBwo&p(O~sLnj{0*05hU0GFp`TbiZ3mP_jHH zMr&7b?l$NMw?$zBDlIw|sDl!aU|hKhiq*FTA_eLUak8V~3|$&~20s}Ni9pKv>Nr(c zW{@3xL#;3a44+t&h4Z}>MX_=dBdDywcWpqDl&jZXt=>)iSwIG$g!t*11@7YQ{mHY& z(o(EA*d0&z3gx8hT6MTZlVKX8YRBcJ5%xmZDqwJdys~YR$Ojc^gJ-3XaaEz|0&McG zz0cL;TtddmsFZbmRhSHu-l7eWVd?B{i!Js^%QhWmvi?W?P-b~JVBJj?flRF2Efm%zd8SmXQr zkz?%($@*)ZzuU3)g`~bCJ~H$dlAhk|Et1Fa<@-|7@fFUsXT?;NNEdx(aG@$)nIez3 zgCOenbn(KVhd#`-lWZx!V#BYgOwX={Kadbk49)N4>~t5aiG7%qVw1Jf0VjXIFC|@A zZ`>abe0*8{lkY>C!5(#bOeU+q(F}s1S&aFZtjH#Zf5?a=!7j=i!Bheas7N@Hkwr@^ z48fl{$n!W{>+{nmOxO@#>JL4x$`}K8a4cl00X4eRNrd=vEOFs}hF_N324c?Ah4T`lI9kE~GeJe?tK&10G0l|6QPhnX z@kQb66yMF2YWa*ryZ{+zB+~u8gt#Z4uN*;tPo9&ng?QH1I=`B9{0+pjt3^{WY57YYGat829lC>OG|{>u_#6=iN9sy{pEI8gF_U3`xH z5jfj>qPNjp{MK1gKcY91c^v%)1;S)4R+&*~QguZwWg^x9{WqAfZX`;t{-lT@2wb z9ToigCql(n{r+OeXago(AtDZz>6Wb67v3Yc@q7}%BMj$tFaho&4vh*!ag^9~~Z{PgnR4>NcM+c7`Be;2F|AE6u zNKaovlN?PVKW6Uax7PfS|D-^Z$nQ^trf+vNaqaobB)zhJ*2GRP3EhsS?kHT5psjWL zThgpO_lHW-5(8IOda+B|bY4=on$k{nb7r3!qRd-9<$GY;sY(j|_k>WmpG{#B zL?65*?Ra;Z)PEvH5n&lZ7txaA#V5`bGcUWrjSVQSgoaB;g-rzh?`|LCx_ioF$EugL zuB7STm+J`KF-ZK<$<^=Wjzv`Nu8ub!3PaKg%I>(k;&~#m40fhd1LWwq1l6z#l8|!< z(KFgUv`HlrxA@ezKtiF>pDCb)TL^4Xd@Gm{(wsiWhoIO3dsw_+ytYes4|F z?@TN8YfAjq#}`7w`p}T?-kPFu-HlYkqd4o^Qly%)iqCXz8c(0X>9}F(T$5yEpRmS! zQ+h$CZ%f0a+*+{CZ-b7r+rlU`ct={jvcB1Nqp%Y8VgN37tvyb|qH7&8??~5g%m>## ze@DuekzK7z;J+*7+j3RNX^fy*Clq~OipeZQ(72PJy&|_cWof1n%o;`cEcVT*>X9`v9{6a4UQTur88=p9>|KItV-lcO8X!KjL zi-}H^xt`<4?08-1+4qqCm|E<4^zo*n764gvAatI=Bk+G;iY-n&l1EVced+((-nqxw zRaE)@?7dGqot^hdcpV^g4iG{}(jkCA2uK4_A^}1t;P`?xohI}p>5l0H3F(2c;_!!l_?WIb zwX4=zwQALC)o*cvcOo4=K?d}LX}Sli@YPb#=!rW_reQSU?!kh|ISw654Kzm;u{mkj z2h#~2*N|Un?t|%!nZ;X&XIY^g;xpMuyf^Pd2DiUtsJxH>-wq5!>ppqYmI2)hcGhnQ z0<7Efj0#sg{Rke)gPWS4iPUbu`K^0!aKkR4#tnOPkd5#Xe<6U!Z3CvwgfNL{GaGvGYs? zpfy#tJAu|heeUfeptVhEfSwy0Xw7)?vfB%^R{Lr>A9oUG?dOj=j*yI|5r2cQy|{Y% zf>#-3g>vyn86X~7isugFa4ZD~QSUJ(k?qOhqilNt7Two(G>FDF>K_e$Pi5KNZrB(= z9{qK&)i5WYvc7L!Pw&?AByBx(5gg+L;20-)zQoIGmwGuds&bCWSd=@P?B#2h+@Cz& z_01&TpK}F+`W(KwbEzMrN+P~uCrfJ~zI2|i9vSNNb~`T%bgAg&S6pU4US2tHtS@7s zeNA(MU5M4j9~X`GyDcE+gELkE(9(Nhvmii} z<%n=oc+D9QWi6+&q|j?|IN_w)w)MJD>Lvk61g!<+kJcIlv?8C`NNId~%0Th=pyz3` z5+?YjcWi}kQ#a4{f}2zA;^x}AgLf%tvd^!;-y?ww4SYkhz(=a`cGwCBtOTGJ|5i51 z4$!M!*{1bRyL10W*1z`S1Zgx871VF%M*51p&5sq#c1>A)WJ}vMTB8fQ>`0ibrKjK3VWjV%Osz|**yWn;w5M0%)AZTe?kAcpkPO}WU2W>PVlTA{^4Wh{7?;g zwj<_Uiv_a-)zk9HO;t7wM|(uMBg0WMS~wA3eEW=i!s&KX$A+i!z5;Ys^Zpp{qdxDc zP?+|{Kw(v>+6f~tXEn(V8Rl$Fe=cl<5u5Khbq}-v46CZf28LCM?IfucFs#}h8WkAU zns1GF>Qm+pP%sKGtQub^-8?>$vBb6|bzszDcz_Ijr^g!?rdr6RO*oG$Ro5>RLw~nAewXh491b z5jB0~g4)~>#e6k7FD_v(uNMbN*{hmw<9DG-hCj7Mc&KatRzKTbp#lI(dtA{~=C-# zi>wro>}9@k5=|xJDXF22JZXJ|Eg#UC>%$O{GJJuC)$5w{~!y$;LqyyJ*Rf zeJp`2t}Pf=wxu}YH;ary~enhuZ_Y`%RU}hJA$FHHI*K= zZ{{YIzI=RGl#Q_{2_+&UJJvUIlSRo31Rec@Lyn5^=JKD=(N`_|6FT}I9UXmvL89|0 zW{&`r&O_HdOAeF{dh1>Qr3-Z(l#IPg2C~63=W2nOzF!?PU4J@W#{PB8bp7d>vr07s z=Ey6V{`AZP0tUx|N~S-*iqBUYkDCrIeHpKv&&$syz@`^>T=Axxt7x3!ix^Vec`I$p zTYGdBjz1NBTWDxGH+5W$kE|vh0Lr}=haQJc4Zgkt*9gvJ!ydJ-1E8UIL2%w0#5cGg zgr<0SX?X4j^Jvlj=0(xmCOmgie-u3T!_vc>@!TaJDCF^>P}O<)bXbA!Ej;(b3Vd%a zJhQ_J{Bb#^&o6gINbQK{Zdsu&UQ#Y9ujGb2;9H9XraC?nYMskl z+ZFeMkn|m{J$f^li&a4^H>BB-O~CC(HUYOE*#z8vRQc#gY!dLlEz5}o+C4j_03#2; z?aC;C+n1(Y&A{zVg42uCrG?;xpS`pYoZf;jEd(cU>Ep{MMp`0pyJZ~}f!j|>muJ;O zaG8j}?P|=FSWcGsC@9Let;(gy&Vn8Uo>Gt?Z1z(M5`@iuN)tBwvhqtK2@#v!vO-;m zY1m+&eCMIQu2O)!l_8ih7C4BS;H#K8`**yYoo77l>Wd0dFs~$0I_?@J~@a-Fa zLiz4(Gn{t_ZiAWLsfK@`6wLJEzUIt;6<%IjUKg2Z3(Q!SQ!6y_3k!v7b7qv`!2kf? zU!QJKFaY1s*84tczwo!$7m^(hG3yJ-j)$1_g=9hTE^jDrj>L=)#8}pBlTCYN-0RXS zd96}u7=gYAj?GD!uPd5sr@7Y^%^Avd=P7}A(6P%~%U8ta+Cy`e<-7|&`_BvB+nsl1 zfFXw{aof2jN#6=N=Y`?s13$b%h~6>v0VtDB0_-Z;}BHOqUQrS1+%z2+_gKwu1|aFv^2?TOinKg6HMYXHLi{9J&YG zAWX1c*%MY${*F|~kb#N@xDv*^^PVHlcY*61lZf+O$&5KMDG#mW@Y91hbHw?-lk)Y2 zICIyRnCU`SsrMy3sFPNWN9cL^2D}zSR%jNHe=sR82_ny3D9za+eef1uaNjf zE^v47($Mn#r?02_00;1yIf&9$S@`L8^x8q-TGvB``HZ+styQrQ%0z_n(YjD3B9xET zg)$NA^wH$-ql1hlBBPHc$8hy(DmM}CKbDklE@U(@$S7p~AJ?c!mA20$=@;Pd>Y!05 zRh_p2%WDJRxcx*6j`OLI1#n;MAK>K)5Cz6H(}!?0Y}4-!ZuE5E-=~BiGSdPaS$W)T z5O2|wvtWD@jDMy+xF#{JeI}W{SKxFKa`;TL_q>>d@y{ejy)-aB3C3?t%AYS7pA;Am znb)8PD8uAR`OYLgt@@i`18FlIBnh0)0|z;L;+Cp72zGAZeN8T~DvULasD|$5`7!nvBBTnJkQx?_}hDXL8i?d_UYK@nO9yDg6t( zk11?EiaiBADz8R)1>Tk5@H$xu-WU8sl75YsG^i>`!o;P8<}hpF!Yu>^N20(G^T?nH z@M~l{@<8O<*p569?}-m7sF-%{(L)Mvme-vm2_d6c0sQKK?Dr(ZkiqSW93=crIgKA^ zgfxO21RvXx1Za`RH<1AG^3CX_?N4gIDKG64tbSq-+?S;HC)gd_YfJw=ZZ+LDZHI zKfrxXOM2eKGpm9qJ;;BcP866gBnzVOR4;$GPLv0ZAqS#*P~4=__E1uK7{y%`w9V{S zd@pEr+xA!nj5adFMsZsiVr+CX#SVi#mx??TqcaFisQklvbOvLx81_N#1`MQ99-YCE zfk=kv3?yOkhl2Z5O)CFBJkrL$#Q+C<;p6FN3UHv#MBD!}DgA0Ubf&MM zN0Ej`z<C7jZLv8%>1r=%oYJB{AsEuF7 zp+*wYf2pA+;WM~@o0Oj24Z^Qq8V?&u8tK1ninZ}nl0LH&st61KR+Nuj6&)ntsi=w$ z67W=1MUu==PbHOShR53YeN;siu~-{VOBEGO0c3$I)6%uPBiOmnJ$1XH(*r3Yiz{Am zdgvZas)7%=Qcnf`f~B0lHoZC}*v32jZQ00R8ybpQYv_eS>qr|`N+4}EC5FYEEkkxW z(gx%;M%uVK<)BY9hez7DIwjJ^ZO#jWK}Ll2WfZ#WNH7(ldZl!w}QOWG7_<1Hy~Mm1D;p8JlpbUn%uCmp~0+KE}G;Cz^N z=8gVhZZp~joO(BVw2k+sP0=>qo9??` z{#v@3h3*H^(mix@FEcY6D|X$D$QMO-7w`XV=V6CSYz%-D6evfr0_4bo4J7CC>>YRp zH{MHoQrGso?B~KZ!EbX*Iy<;nMdex{eh}QC)k9@6471VfZe0oL_qHooMs72NQ zsn4l_nl)g)HruFPZ#4O2f)i{D^3SD+!05LH`R7#qi>-R5|ZqM7A+7ELf!1rX@4PQrTr2k zhdJ?%H2o6fyvWD_vq{nHwnn4yvdqQl*LTjyhEw5tA&a8V6Nhs#7)2srr(r z`lL+PcupzXzLKW@%=^phla9Fy7IgIVZ(PV*&Q5@h76^L?q~C$fOCXuf=0A36fXgxn zb#x{UbYM0xIIv)7ea{fMaQa`dX$5D8BY*+mvKr$o7Nt44<4CB72YF~e#|O9_@{&NUrhs$#dw{9liY9r z{8s0RW9)wtS08D?l}>GUBUkP!a+&_QJbKPWXR=}3S(*6wqu`DZmm)ZFC-j4Vs&mJ& zI!U-Yp9ujIb#GewJ`=)f8vtRORLldWP`c3D&dugYnkt4({HSyJ-n6}%Ux0G!jcwcg zY5HC4?>V8#0O25?nxfa^9q@=#aXZJ{EX5B-f&*O6resR&h%cBu+Cd65A8t4Sh=`_q}<#qL%(7*WPYxE^Txc3S>UdWan#D9`N21G3f!882}5J)6&1vA3GNiuf8mdo{z&iL$?GE zr|o;?$H9PJ^R_*braz@K{NSk=WR0Cs-#Z(JLBjshmakpH{?hi5I2-y)+ehMTND>J@ zl2(2iWQ>QOrA(By~LIOPq14gARR6jK5XpBiDTUL`tN}*PFV#-P_PJ1eQuuq{@EK zZR|(4yZne!$B9O#+q)j95?Y`fVtk?^X|#pulO&Wsp@~Y;=c3_PY3ZrmApHgh&|%uB z`-ERf`qIXU(#9v#^mjX>jeN{_=WEwSl2rX<)JBr9_GHvXl4#?TY2|l88RY6pJ(trC$#ik}23ofa&uWYG3dAu<;&?7i-;kB7%UfH@ z`ry=TD03O_4==fJFnSwE)z;H$7`jxAu&CRGMUsY}i^h>8!g?+mN0JEZxpd|mGB=LO zFyr`#w0vde#!-1DuB$S{Whg|Gr1)>n*#Cn z*apVCK3?HB-TlW6E_avYvmY6D@gG0ZP4Ld#`-@7X2$?QLk}&bHEI=%gM2a8Fz>AUM zkz_0Pv24b1wt!L6Y~aVTnM?A`#xpy)Ph{y$*^=s77qp#t){V3oKj%H3X!dQM-?64q ztZUp!AxMZjUhcH58pA2#$~U@BgwZm^G=XL#57LBBWB~$&U*X{sSy=j##JYbXn|V`q ztSx<&Vb=W<*&a7#$9Ul6DYAUG$dzQ))r@LF_I%-u4mfEyfzG~Oz<7C?QbX{1gS)h__1LdzGj_WkmgA>^qV z@PC`7bE->eoc)?_@J-`&e;F{0J=o1)2q-*=I&06#KEwjX1+J+Ji%(?^V@Hyf{x;id zwv9uQaQ(O0K?fVx(<*IW&PxAx6s}{fyO(QT*OtF5uJHpcPZQT)(R_ADhg);^(XdcZ zGIeksMzR^ez#yM7!||QZa3taPD{+P+NgH2@GaO0y{fcI|$E42Fr0oBw8SbH7J?n1l z+ueHHZL)ZEWA#z7ndRi9&s8EZUW46V|u1XxA2O zI-1n>oh*GI>kJ11Itpz(o7FgW*Q2`6R6(G2mwfHJOX`Ba?_^mEpCczh1aU{-%516c3q@C9W4G%HWVcC7*?zMta=%(af< z>Ww%1cG$cm4S7)E8Sv8F4W?qwqk?gzv5zyB*g!h7Gv6d&8W2fGAlia z&hPT>tN!Y5n7x_-Q@_;i3mB*J3~BtYHCxRy&6AO`*Z@OY3zkixYVtPt`VI^9S-4wwtl>`(J=S!@0zqG(50eOit{^0l z%NxqXG`CJM1$jf6?de=&h9BPuQ`M@G&}jCW{Q+m%@S><+Ka#XB5w=&W;q}IHWk!L& z_|{eVoPcB)eKv}hx-odf3lM#AR-oDL>xoj)xi-X;+8*G=1BQQG+;4`j1I}cpU={HN z-n?bVf2duT=IyKGKTSvt#<%R=o%uMdd(YMY3bs!y8pXBnlpwBdFSq2l z$GeWP$f%>DutgdxGowlX#uop)ymob#PhVwg3JxKPvMt54cY%*)e` z;Esr-N9`;;ibk|JsszFB`s0YOa&SH+b{r5>Yx`bjuzusZC&%37%3SjD$GcYNhZfwp zD#obToghRafWjAu@Q>)MK_^;9mK{ zE)OlZ65L#K5Pm9IY;^qx-abHm0Y9y#o-qq1b zqI+ui=9KVB<;8g+Zb!MwwuN%lJt_8&s;!)mN5X(o)d&*4*u=$SjG##c4HRz}rH;=y z#wcB~C+^J7Z?(@pJM$ zPPScIy^HL8yK;Qq9*c%qW%jnaxA>%XSw1V&J5trWfmh^}LJbRB6`C4jP8?C)^rDu? zLhYP<&n_2n%nAoIm8DG+^W3MqYTKUL>R^`dP4WX`#UtqOw^LZF#;O1Cr@Ic@0h3-d zRXHr5ibK-o^AyP~%o#%E8>huY(mh$fy@a1^;;1bp3~S(bBw4;-VD%X1Qj>9gYOS4{ z?~MmUT~eABqP$LO;%4E~U30fr{R&oU8}r$!e? z|JR;Rjr^?gD4rGG%uQ+5^vc4P3f){V2&1~~0Z{8S{F_;|%7~Tn(2`6{wC_cQlZ=K@d)ebEgWu!jTHA-gXQ(&TwP^QY^Eg2b6 zHp=>tmY>9q4F>F3qkn#7UP1q5Ql#UD3gb6#n9aL9f{Z`i3Ag^zO=0bLV_;G3uL$BGpv0|~Q&$mRpONj9(u zJFV>6*u(qt_{;o`b3oMQ{HkN|!bKf(b(~oXAJq;es^ZqcEf%^)kwdwXrUnkW?G?Tv zA8!PoMsZj+Y+T>pqv(?MNLZDGIyfqMMW|u${1B|A7kZ;RV<^T!I>dG~1;FSrIxYCc zdgo%ObH(zLm!0t^3?+hTts~;bCW}E2LfwY`A$1}CaRbC7Ti?$UcaKlq(CtNs7}gQc zHPcFS>`#y%rk7^hpTIs;0vHky6EjK&S}t%7Gr>g?MAC2!B?nG245it^JEDSp3gD!D z>%d9+)8UZzs{<$LPtV-H4xFSvJ#$taI7xrzhMQFGDE%2=Z~=a(19!~`KXhOd{1B<< z6MhH>9UfhCusA23pW&e6b2{?p3eyjTINftJ436`%Ic+mz3JJ~GV_r-ld6I0wu++x8C>sK+{IEsZJY z>3r#*1$w{`DlaM@5$TC2LzdMyECbChLNXSE{w(Su};2m*x>Ynps3W82OdPN{e*JjJhDDq5XiEeP)cOy6odvqAZ1_*xEd_KvNT|(K=*suE8C|zegSV1UX`9( zRx1uz;K_-co@>NrYf__539Q)~uAgYl?*Owk+!==yw65VEGNgcpTf-iiai@}YA)Bq4 zv6Psl)XF_d*|3L>6quW0N7mgmbXkqdm10MQ{?&vzd=RJ(c<9B?=tQnwNQu(E^6cv2 zcFga`y}|2EL965mLbaSO_7mPyFP(aPM~K;(!tIIGfbjdud(_jk(6{G)^)xK@9nfKM zS5=;$FDxGdfYNHF@16~cerL0^?z!Q@4#8lLCIvb}nRr~*&?fiXR8nt4#^%EPYek#f zI%F3fJcsaI>J5I}kk+ajJK`c=?ZsNn9mcP6B{Cps5Ucp^WBF3BJKX&{c(E3>=pBs& zwP6FXw0OhRapq}mnbkb{wSj9o?_-g^Vd9LK5^XchN~$DeZ|Infg6Un=xQ(T^Ca!tn zZzFEWde4`jd9O`3yXGZ&z~@P6o}dJ>i-YEoK=UpRnrDas*~LNg3@{+OIA|UzH1Fb| zc}mF@AiEgNJJM>U`K<)$I>h>nizvk!p>M*ywC@|DlN?I}V=j@W2%ov)lTszb<&qdk z!Rl6`@#>y8L9@rbK7AvQGdr)^R6+x<52{T{qPSw`RoiNyudWEHZE0G#BB-{dVd4r@ z`(y@_(oBq3B|EFzx}LO3xTd3){jdTd!>UEQiwvfhs}j_kh!^$=6W}!oH;?nIf9x)x zv3GQzM2yhEEriA9NrT>z`t_)qliMC2Pbg{^7eox+yPiRF*CgBwUSYaGW7j7CBg09i zHc2&=L4aR-lSEwCCJdd+OJI*Qj-``JSTcbQu;JwO5;d;z9VTrfRZG5 z7yHg6eRn{hN$p*1$e0A%088M~oG`LfFDax((tQd@QrC46D}W@eUMH-8P?#ZlUBc+n zD;s`wN1N*shSv(!tqbz&lk{fve`!-}=1u**I0H1<-v$dmG{VGNb9TLcJtro(!?me$ zk^X+EhlA$?3*OWS8^Lw&YXXy`YAR|N3|-3ns0l}j<kWQ?KP;dNJ7so z$wc=i$7R`?o8j(rB%$S&WYz&@JOGlpH7R`~7!OJ4Rw3ZXcw`ulzfRKIg7L`Ac!UfY z55t7HJsJ;E3@nmvJRJPx_GmmD{N?s&JV;_ZZjZ)8N%PXXJsOWp#^Z}g`cJ#Xcu*UR zeK8sjk}@85?4a?m&)|{o+;~_9732Hu(~4yv-8-W3PzD9=+(qMI)zGKZ<3rOjtm0ri zEQ6NsjK)J57>~RDNXEmOgF@P?Qz+K&ipIlAK;d15@lXyKz@xpujE4~hGf?Iu*fL<| zYteXEhS463hcXz0ckiI_u+M0T@7#D;1})tkjfZ8>(%sQ`fJIa(e|`5E59)((DsgFnQ35} z0c+3@{8A7aFS zD^h8DBuRf7h#?IzWH>P-Dg8(!h9shUBoadsVjf8TRv#%tP; zvVH8@#&v7XBMp!z9A+Zyy4c5VVTGcT_4R}6`gZ)_dU~nR=Td zk5w(W1w-&e(mvOoY4Di8QvO9!Y$}5!V$f=M45HfPH{f9g=QBE)@4S;qQt2;}5bl{I z{QM$eUn%9`E&s2R((i-v=;8gZllBf%9^Sh1{y0gW3d%#8ddcv5NmBaBs5~U8_sOU{ zB$30DN#!ZzB(wr$NO{_RlK@7x$ka!9rar%my3A|(XOhxY+^a|$diVZJ(tfCs!<%&; zHz(!)PjU43}Ie&nh z!Wr|b%kqPRZ(?-+C~mI;jLGxli@8r|7Vo1@ln8*6-oEW{rK|yaJbo3Puju=zv2jnz z$8#>GpUs!|#ID9v!4Sog7tq!0NY=0s!MTwd$WXGRYJ%L#Xq1kxKHN(Vod zj+U2{fu-*FLGAQ#ao$wnh{(#bw@Glf`BBu)%4g`Ab7-cBPTCYbQ_=ofN6$?8bwYPT z^vu`iGn=ano+V4=DP&~F5X;+UyZBFiX7ZEl3wfSzV@fS(H z$FM4cj84znWd7H0HpQ5-xOMQyQNNe}Dj#=;N;sgHph15g(dDD_U2B=Ireyb)f$nyF z!XHDmQ}Z^jQ1LLkm#sQ`#p;pqFjsc1TD9yHkB9k^uH`HEJFQH~^W|rpeCFvZLrlys zwB=>hKk5j7RX&{vq2Msv)#G{V!Dw3_#(Hbl8`ZXOS^cvW`l@?cLq(QT*>>ppm*zR% z@O>MZz&8)!tSM*f)@~)%?n$wHcf+UEzsm9n#V@0BI*b?}IujcZfh#MDIGN`AJ8|*i zmZqVZl7-6$E*|VP33kU&o0Z;tM$g){{SI(_UYK|zk2_OyrCwbyW<%9g^mWlTn$qTr zgy23FQk4a`@c|Og8OEi3Ya=Pv%agjN*MAAME;;w{u2~?NO zH88{a#{!9kuI*HGZU6i7+WGmk;mT8)o$tTw&sHuwd3BdXeqFKboMkJ9>H8#H!IzzN z_VRAi_^J8C?qz8C>C4VI#nhgk&s?dGyH-rgmYno>*NgN0TJfOns~oTm@@sdb`MBjn zLtFYPM-%CN>qhr{o3i-8mTF<87p|r#!QlD-%E_|3Oriao-I;&N7~1V0uL{Mxix0Ow zjF{}oYLtld(^kJ?<+5Rdo5&=8+VYhvO>QJsBC_RYycAPW&G(e4=th#O&pY|dGhVX1 z`*iC7Lg_MPL|Sl6oVkh~>0ZA26~pSDkdIr|-F;>^Hi(*E-qn4E)m(dfl26l2BuN)D z+tMPYvAHatz&(f;&glA+RO6k zJ_lRtVFHGN2G7myp+LoJug|BmbnCxh>#o-&+tf2KbV=W)V0S`FKChlXgwf6BPU?LRZ6X9-fR2S zrWfn~Xls_l#bo7*JU7ouGn`|D@2nTv;r1)lqW$Rp=W9U19ar8&(8zfTi;cHl zBn>Mb5^O&1($*+=`|pxMcQT^a2Uk`OGUqz|QPX0XzTXZ2G)9o4SW7?iw>n2L}hz zJqicXz3L96`qSM)_pUpT>QB$yr&L7V)SsSNtvitFPY_`gd9ysbbWu|MVG?|`@GRD~ z=mkB!{p;m5i(Au{0rRUBzArbYx&|lAkPeS!83`Schpki`|(y zMRDVcGxP>|;g~11y($+D^@Sh@_ku2Lui}d`T!sRFV|T$;`I5Zj@P!?7d(Pj~v*3h_ zde-_MJ?nce>bbOM!=ZV{;zK)Lbq0>U^67rft6sCDW6j3Fi~2SU4)97~9@OL@OX~S_kiCmzdAYP!%Jb6Btopg6!`DCZZXD>lBp!w%TQkou zL>b}_B@S>cn%8D-VM^iNIB(`$PO4ic?4-RLo^Swz$n)vZz=-x{Hg@mvYcrydXw)($&`y<)dPw(MQ*^ zz%A!%?of}F6K)NceDv4uLwdJt+GL($v>zMSZGf}I{akh|@!dj-){iB;TS(FRv4<}U zEbGQ_NqK2(J^JHX)*Ne{^Y9bXQ?lybA@X2gIyPFg=^nRH%;s@hh#4n`?8GBZ4Q-C) zar-XUI;dKno}N{&OmIBbv$Gh!GWbL2Qm0M<_azM55a?F1!f;)%kJbVOhEbq@E@50< z=;OcR!k&wPn~^7oJ$t}FteuZh;HHU-B01%I^uG1$w`?r9ll$)SLW$(QyS(5I$BJxu z!JXW9UpCTx*Rl%#+?DBS`RA%Xtvk(j*j1Hr1?KtSK+(4Rb5|BYOXZ)tvIttL5S=TF zpr!K2J*&Jb_Ga|RwX7ezWVx+;wSt!3pLB5U!n2J2&BPa6+XrOXfZ5R^NO0(A$Z+{? z!b-)ExT3e?f=z(3Hh^oaDOQwgI`H&aKQv!LMY4YPX7&{?RQF)98VqNtZ_}p1O+_ny zX5}7__De@UecfDx9V=TezjjOiCN8v8Ss^Y30ey8b^b`d2)y2?L5YSf_QD+4u^qTT{ zQCu+ysAYY|#f3-c1?m6FsvnjjuA{qfVU>FM`cU(Z+W^tO9ED;w8A91WH3~m)*>>^Z zddY25_+E18;Q@|9-T7`8{-gzY2d=p`O>xU7mK4Vi#SS9j%{-pMRHRG54SjrSPQ5^B z4HmpB=I8|l?}|BkLBYFXj$S~NOt*D{O*k$Kv9?caY!1aCJqusoYz@{})Y! zHw1tmp2Ayh1@KbG((^mcN4^%1!^bmYRU;+HOrbHGDz+<6k<5iBH_AwfnbdsEH!-W~ zs*vz_<)QTAMqhJFUPbTAPrQ;{%E8!XyO7nwKlV;E_x8i`QwpRQEeF&q=f0|E!KJS` z>>!kaRfjr}|MUPWbmH3i#o~jN#URjVtWOw!D8eSjOpJdm67clBl*>wtw^H=)rA;pG zm*NX4Pv4R{?DF)@=IOf{4T(`$?IgM*NUAC1Fm7G-6_7Vz!nu6>l>9P0>!?!G|CP9) z5Rmiife5g(Hr8gao*R3HLZ7hKvc^LANnaQENDfZjL_ip%C(IH+BA$Sw3POTvRStud8+QduFJd^qVM9eX)PqG573&&Hd|b_(>G%(%MVAYM}+QW%vMtJIOdj z%LzQWu5a@~0!qjOPff~gh8lV795bwmiIZ}kxr?Mq`K<{+qzkb%ZrK(ZUs26Xk%H=} zb(17ot$S_0#Do=~_Sa_6%4IgtZPsM+9f%m!{#Dww+&+5cZzPFG=`)kNABN{NkQ` zeNy@W{LVExH~CR$!EgOot(jT%$n^?=#>8!o%5CpY(i@U9sPK0DHw7zte-deNqr@O%STTB7N$lL?iwQ3p;GRN}rb zBx&IzNr0p!iSR!n;h$&?^5b9PhE-i`4XPgOz(sun^Q{Ad+%#kw785F^1+6zHWK61X zNxDPWUnT+O+a1FGQm$J^AtoHcZc0j@K}?4*jKVxEpH)qpt!3oyvgq}ENH)*0o8{ov z)X_lB_lZmwN&!zuX(m&OJGCUy%$uY88cF!SISKA-BoWTda$j3#E%D>06Yx!6VZy27 zg9Zs{^)s+lyDMOy@kZJj0DWzV5mo_aN-?A+Sp~hd#VyvDBdMs3IOQWlT5=hZw1xw^ zC`qXLw0uS-L)_m!o0M)3GHkXDO~QHDzx&!LMc z4S5uI^4yQ^wm4WwLf&n0u#jZ1+?G`SCJYv3*kJh^4VL5JfS_+*OiF(T2Mf%YYMzO( zZc+x{AgD80J~V74%*M$x?~CF?aij2@Ba%{*ehEH0M&ZM2vQ(uxfF02ih!{Qdq_6i-k@7&5XN5A;G0va?~S`}VLLk5j}EdkN;MWGSW zc(G2c&S~nV3wvy1#}d+ZI~)}C6Uj%WEY>XQ_^=_vYNBQwFRX2P?4G1NBY-HzX%6!H z2Og9h8OOTH++o`vSXQtWbb$mIjKXnc-EyFXeqcXhl! znX#W)XLohHU(UgD4MdwCNJ^gwzIgIXd>{s+Zby^9o1{3U!aebU%$q-CT&)$ixh_7; zLae&Qy0CG{Et)ZdTH4yypmQGK`H1gcEdMQ(G}32@!CBqf1=+cB%2(DCvMam!??#K5RM z-x^9KG*@eY1<7E6^crUi8dT9iHvU5yfEKLD2X4f;& zpr0flgdZNhpuoQ+<>}Sgu9DW<>SNX?z1r)(=%W6Oqc-V!0XgcaI+bj~Uq=`^U_vv!P_ZsR@+WT3>^_L4q1$$Y*LHL7m$@p%M6ZQGyIfTvn%7KQ&B(4LYzr;$y!X zlx7!%C-w&hqu_j(#+u!n476q#PDqgB@V0kFimm%Ik90N2SB4Ym)iqRx^LNrvJ)|Yp zn4EsoLxb_B6QdtnhxxIEwLZhZ4T+g9k6*@T{!Gc^mpzlrI4J%~k3EwdGB=-RP0-+T ziXXop#}y5}V)0O*sbW3;q;Rw$BJa5vIKJItHaw@m@z&zJVMiL1DgY9nZc5=mj zo`;1x$FTyJ#AmH&JtKl~(8p;Wrv^iVYFU%?1_m?{JI>$2@@jqmMSUG7FI(XQlT|1b zUV^ie%BjBj9m{!?4xY&nv#(C|D2v;^jAPGQR=6(nO!n`ZG!N11GEQjP-k1{WS0`2D zB`TXWLe>J=Cf>bZBj2Xbp8F4*HmJRjWz;1Vr*kOp6TW>Q#P{xW(w=!Y-t#o!!nrPO+dI7U1NWK^el3Ut!a&CeG#+b( z3$fUO@8flXd68`-rsor4ov=owljxKp3lUwHPM*=21$);i4)YlWF%-H!Z9C8cXXwnw zHy7TJpBviIe$>ra00|H991&dRO;VM5tCBGlPHfDwHYUw#%z}{X)7drl2Cgs+-6z~))zBtX4%Ivv|awROm* z2Q@b<>Y~CrPtX$cQ;IB{g_EDP{TEz-;JKpSIB3fgR97CRW^%3OcyhwGRQ0KJ{6t$$ zl9Z{uB`xn`md?@?AY*1dgRyZ-%G@N=rxFynH7!qz8%AxVC7l6n)*zl`PR~D>l zb<$_!G7!hfl?4@OAW_Ny1=T_VTCaRQ-G5fjy{d&LRaoU|+^cHDsr%wO!g`RJq(!`S zLdPiB7L!zahx#-83ZHjKtTodV4tDQM)32c^m5%7J>+7GoMrabcGaWxQXoQ{NemMxYC}jckhK<0&d*`#Dju&Q?w)@ib{`8FM6jPVx9V@>> z5Cxndl6-w%jCn~Cg6@kkFG;dRzb~D6f9faA%CG~c`%?~_6wBP=x;~I{MC{;2BaetR zp3Ihxem+bE5JU}rKJ39*A5buDX{`rieIO0z!@0WnL3QfRo)1$4%~3_FLB-)b~;Q^ zCJoBE9+E^YAC5ulNmB2_>9jpeG$f(*;dJkP>~wgd82L&1{GSff5E7&%mmo=NIGhfX zgsPv&0_deG(PDp=mVSW*=QCI&Djq3m-qtL}Mu90>12TGH^;nUh*9rssvy|J{H|o5H z(5jU-q76Tup7uX^;sY6Q4;{`uNvM1*2G}JD_ZIb7r&c5xKaZuA$5RjPtPC4JkEiA3 zA-pZ${~Wcho;G~0FVHnLf+QllLoLD|$CVI2*c@ArRTJg|;a9r0vEfY6LFOHxM}(udT5_Q)x#>P z`3Rq)NU;c0?4e7GFvT9avBofH;skHP4JXmEA6>;+^ zQFQ`(LpaJx+tX?K3{?3Qsfm-do%!}KiwDPw=yTzdb$^VF%lD8<1>WH#sr~8L;Uwws zr(;BAl92jzT6rdrsthCb8IdY;KwwF>_h~vKn1j%|oijEp?PUBYO4F3}4kT%xwokF~ zPm-peOF0f!)GmTMf=8w3cOJFN>%{|6o;R^#ZKaE4u{Qp`#5H$h7BQh-IeJl3k%Wk= zVhlc-frzWJ>5h~@5+bfrs5u?z5^3=oLK=mBP#nZ-6k};U^jRFlH?gp(o?BOR$g#F# zA86U7O@EBK6b{PceYsz1@sapx`p`bnqx_)z9x0LLTy!2O@l7%Gm`6%{6QRfA8|?oN D1qkIR literal 0 HcmV?d00001 diff --git a/packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json b/packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json new file mode 100644 index 000000000000..17b4598a92d2 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json @@ -0,0 +1,90 @@ +{ + "methodConfig": [ + { + "name": [ + {"service": "google.showcase.v1beta1.Echo"}, + {"service": "google.showcase.v1beta1.Messaging"}, + {"service": "google.showcase.v1beta1.SequenceService"} + ], + "timeout": "5s" + }, + { + "name": [ + { + "service": "google.showcase.v1beta1.Echo", + "method": "Echo" + }, + { + "service": "google.showcase.v1beta1.Echo", + "method": "Expand" + }, + { + "service": "google.showcase.v1beta1.Echo", + "method": "PagedExpand" + }, + { + "service": "google.showcase.v1beta1.Messaging", + "method": "GetRoom" + }, + { + "service": "google.showcase.v1beta1.Messaging", + "method": "ListRooms" + }, + { + "service": "google.showcase.v1beta1.Messaging", + "method": "GetBlurb" + }, + { + "service": "google.showcase.v1beta1.Messaging", + "method": "ListBlurbs" + }, + { + "service": "google.showcase.v1beta1.Messaging", + "method": "SearchBlurbs" + }, + { + "service": "google.showcase.v1beta1.Messaging", + "method": "Connect" + }, + { + "service": "google.showcase.v1beta1.SequenceService", + "method": "AttemptSequence" + } + ], + "retryPolicy": { + "maxAttempts": 3, + "maxBackoff": "3s", + "initialBackoff": "0.1s", + "backoffMultiplier": 2, + "retryableStatusCodes": [ + "UNAVAILABLE", + "UNKNOWN" + ] + }, + "timeout": "10s" + }, + { + "name": [ + { + "service": "google.showcase.v1beta1.Identity", + "method": "GetUser" + }, + { + "service": "google.showcase.v1beta1.Identity", + "method": "ListUsers" + } + ], + "retryPolicy": { + "maxAttempts": 5, + "maxBackoff": "3s", + "initialBackoff": "0.2s", + "backoffMultiplier": 2, + "retryableStatusCodes": [ + "UNAVAILABLE", + "UNKNOWN" + ] + }, + "timeout": "5s" + } + ] +} diff --git a/packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml b/packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml new file mode 100644 index 000000000000..a28ee5b2f64a --- /dev/null +++ b/packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml @@ -0,0 +1,91 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.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. + +type: google.api.Service +config_version: 3 +name: showcase.googleapis.com +title: Client Libraries Showcase API + +apis: +- name: google.showcase.v1beta1.Compliance +- name: google.showcase.v1beta1.Echo +- name: google.showcase.v1beta1.Identity +- name: google.showcase.v1beta1.Messaging +- name: google.showcase.v1beta1.SequenceService +- name: google.showcase.v1beta1.Testing +# Mix-in services +- name: 'google.cloud.location.Locations' +- name: 'google.iam.v1.IAMPolicy' +- name: 'google.longrunning.Operations' + +documentation: + summary: |- + Showcase represents both a model API and an integration testing surface for + client library generator consumption. + +backend: + rules: + - selector: 'google.cloud.location.Locations.*' + deadline: 60.0 + - selector: 'google.iam.v1.IAMPolicy.*' + deadline: 60.0 + - selector: 'google.longrunning.Operations.*' + deadline: 60.0 + +http: + rules: + - selector: google.cloud.location.Locations.ListLocations + get: '/v1beta1/{name=projects/*}/locations' + - selector: google.cloud.location.Locations.GetLocation + get: '/v1beta1/{name=projects/*/locations/*}' + - selector: google.iam.v1.IAMPolicy.SetIamPolicy + post: '/v1beta1/{resource=users/*}:setIamPolicy' + body: '*' + additional_bindings: + - post: '/v1beta1/{resource=rooms/*}:setIamPolicy' + body: '*' + - post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy' + body: '*' + - post: '/v1beta1/{resource=sequences/*}:setIamPolicy' + body: '*' + - selector: google.iam.v1.IAMPolicy.GetIamPolicy + get: '/v1beta1/{resource=users/*}:getIamPolicy' + additional_bindings: + - get: '/v1beta1/{resource=rooms/*}:getIamPolicy' + - get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy' + - get: '/v1beta1/{resource=sequences/*}:getIamPolicy' + - selector: google.iam.v1.IAMPolicy.TestIamPermissions + post: '/v1beta1/{resource=users/*}:testIamPermissions' + body: '*' + additional_bindings: + - post: '/v1beta1/{resource=rooms/*}:testIamPermissions' + body: '*' + - post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions' + body: '*' + - post: '/v1beta1/{resource=sequences/*}:testIamPermissions' + body: '*' + - selector: google.longrunning.Operations.ListOperations + get: '/v1beta1/operations' + - selector: google.longrunning.Operations.GetOperation + get: '/v1beta1/{name=operations/**}' + - selector: google.longrunning.Operations.DeleteOperation + delete: '/v1beta1/{name=operations/**}' + - selector: google.longrunning.Operations.CancelOperation + post: '/v1beta1/{name=operations/**}:cancel' +publishing: + method_settings: + - selector: google.showcase.v1beta1.Echo.Echo + auto_populated_fields: + - request_id + - other_request_id diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt new file mode 100644 index 000000000000..0ce4b3d6e6f5 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt @@ -0,0 +1,12 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 +google-api-core==2.25.0 +google-auth==2.14.1 +grpcio==1.59.0 +proto-plus==1.26.1 +protobuf==6.33.5 +grpc-google-iam-v1==0.14.2 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt new file mode 100644 index 000000000000..1cd0c5a2c3d4 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf +# cryptography is a direct dependency of google-auth +cryptography +grpc-google-iam-v1 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt new file mode 100644 index 000000000000..1cd0c5a2c3d4 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf +# cryptography is a direct dependency of google-auth +cryptography +grpc-google-iam-v1 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt new file mode 100644 index 000000000000..f85022a2fb62 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt @@ -0,0 +1,13 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +grpcio>=1 +proto-plus>=1 +protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt new file mode 100644 index 000000000000..f85022a2fb62 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt @@ -0,0 +1,13 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +grpcio>=1 +proto-plus>=1 +protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt new file mode 100644 index 000000000000..f85022a2fb62 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt @@ -0,0 +1,13 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +grpcio>=1 +proto-plus>=1 +protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/gapic-generator/generated_showcase/tests/__init__.py b/packages/gapic-generator/generated_showcase/tests/__init__.py new file mode 100644 index 000000000000..c4290ea03f84 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/__init__.py b/packages/gapic-generator/generated_showcase/tests/unit/__init__.py new file mode 100644 index 000000000000..c4290ea03f84 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..c4290ea03f84 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py new file mode 100644 index 000000000000..c4290ea03f84 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py new file mode 100644 index 000000000000..35e420746ddf --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py @@ -0,0 +1,9408 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 asyncio +import re +from unittest import mock +from unittest.mock import AsyncMock + +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 collections.abc import Sequence, Mapping +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 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.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.showcase_v1beta1.services.echo import EchoAsyncClient +from google.showcase_v1beta1.services.echo import EchoClient +from google.showcase_v1beta1.services.echo import pagers +from google.showcase_v1beta1.services.echo import transports +from google.showcase_v1beta1.types import echo as gs_echo +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.any_pb2 as any_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +try: + from google.api_core import version_header + HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + HAS_GOOGLE_API_CORE_VERSION_HEADER = False + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) +_UUID4_RE = re.compile(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}") + + +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 + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert EchoClient._get_default_mtls_endpoint(None) is None + assert EchoClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EchoClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EchoClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EchoClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EchoClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert EchoClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + +def test__read_environment_variables(): + assert EchoClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EchoClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EchoClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + EchoClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert EchoClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert EchoClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EchoClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EchoClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EchoClient._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 EchoClient._read_environment_variables() == (False, "auto", "foo.com") + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): + assert EchoClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): + assert EchoClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EchoClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EchoClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert EchoClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): + assert EchoClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert EchoClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): + assert EchoClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert EchoClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + with pytest.raises(ValueError): + EchoClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + assert EchoClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert EchoClient._use_client_cert_effective() is False + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert EchoClient._get_client_cert_source(None, False) is None + assert EchoClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EchoClient._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 EchoClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EchoClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) +@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EchoClient._DEFAULT_UNIVERSE + default_endpoint = EchoClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EchoClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EchoClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EchoClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EchoClient.DEFAULT_MTLS_ENDPOINT + assert EchoClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EchoClient._get_api_endpoint(None, None, default_universe, "always") == EchoClient.DEFAULT_MTLS_ENDPOINT + assert EchoClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EchoClient.DEFAULT_MTLS_ENDPOINT + assert EchoClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EchoClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EchoClient._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." + +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_echo_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__' + ) as call: + client.echo() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_echo_error_details_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.echo_error_details), + '__call__' + ) as call: + client.echo_error_details() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_expand_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__' + ) as call: + client.expand() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_collect_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect), + '__call__' + ) as call: + client.collect() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_chat_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.chat), + '__call__' + ) as call: + client.chat() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_paged_expand_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__' + ) as call: + client.paged_expand() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_paged_expand_legacy_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__' + ) as call: + client.paged_expand_legacy() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_paged_expand_legacy_mapped_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__' + ) as call: + client.paged_expand_legacy_mapped() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_wait_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.wait), + '__call__' + ) as call: + client.wait() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") +@pytest.mark.parametrize("transport_name", [ + ("grpc"), + ("rest"), +]) +def test_block_api_version_header(transport_name): + client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.19.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.block), + '__call__' + ) as call: + client.block() + + # Establish that the api version header was sent. + _, _, kw = call.mock_calls[0] + assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") + else: + pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert EchoClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EchoClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EchoClient._get_universe_domain(None, None) == EchoClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EchoClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = EchoClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = EchoClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +def test__setup_request_id(): + class MockRequest: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + def __contains__(self, key): + return hasattr(self, key) + + class MockProtoRequest: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + def HasField(self, key): + return hasattr(self, key) + + # Test with proto3 optional field not in request + request = MockRequest() + EchoClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with proto3 optional field already in request + request = MockRequest(request_id="already_set") + EchoClient._setup_request_id(request, "request_id", True) + assert request.request_id == "already_set" + + # Test with non-proto3 optional field empty + request = MockRequest(request_id="") + EchoClient._setup_request_id(request, "request_id", False) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with non-proto3 optional field already set + request = MockRequest(request_id="already_set") + EchoClient._setup_request_id(request, "request_id", False) + assert request.request_id == "already_set" + + # Test with proto3 optional field not in request (MockProtoRequest) + request = MockProtoRequest() + EchoClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with proto3 optional field already in request (MockProtoRequest) + request = MockProtoRequest(request_id="already_set") + EchoClient._setup_request_id(request, "request_id", True) + assert request.request_id == "already_set" + + # Test with ValueError + class MockValueErrorRequest: + def HasField(self, key): + raise ValueError("Mismatched field") + def __contains__(self, key): + return hasattr(self, key) + + request = MockValueErrorRequest() + EchoClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with dict and proto3 optional field not in request + request = {} + EchoClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) + + # Test with dict and proto3 optional field already in request + request = {"request_id": "already_set"} + EchoClient._setup_request_id(request, "request_id", True) + assert request["request_id"] == "already_set" + + # Test with dict and non-proto3 optional field empty + request = {"request_id": ""} + EchoClient._setup_request_id(request, "request_id", False) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) + + # Test with dict and non-proto3 optional field already set + request = {"request_id": "already_set"} + EchoClient._setup_request_id(request, "request_id", False) + assert request["request_id"] == "already_set" + +@pytest.mark.parametrize("client_class,transport_name", [ + (EchoClient, "grpc"), + (EchoAsyncClient, "grpc_asyncio"), + (EchoClient, "rest"), +]) +def test_echo_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 == ( + 'localhost:7469' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://localhost:7469' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EchoGrpcTransport, "grpc"), + (transports.EchoGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EchoRestTransport, "rest"), +]) +def test_echo_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", [ + (EchoClient, "grpc"), + (EchoAsyncClient, "grpc_asyncio"), + (EchoClient, "rest"), +]) +def test_echo_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 == ( + 'localhost:7469' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://localhost:7469' + ) + + +def test_echo_client_get_transport_class(): + transport = EchoClient.get_transport_class() + available_transports = [ + transports.EchoGrpcTransport, + transports.EchoRestTransport, + ] + assert transport in available_transports + + transport = EchoClient.get_transport_class("grpc") + assert transport == transports.EchoGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EchoClient, transports.EchoGrpcTransport, "grpc"), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio"), + (EchoClient, transports.EchoRestTransport, "rest"), +]) +@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) +@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) +def test_echo_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(EchoClient, '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(EchoClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EchoClient, transports.EchoGrpcTransport, "grpc", "true"), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EchoClient, transports.EchoGrpcTransport, "grpc", "false"), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EchoClient, transports.EchoRestTransport, "rest", "true"), + (EchoClient, transports.EchoRestTransport, "rest", "false"), +]) +@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) +@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_echo_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", [ + EchoClient, EchoAsyncClient +]) +@mock.patch.object(EchoClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EchoClient)) +@mock.patch.object(EchoAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EchoAsyncClient)) +def test_echo_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + +@pytest.mark.parametrize("client_class", [ + EchoClient, EchoAsyncClient +]) +@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) +@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) +def test_echo_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EchoClient._DEFAULT_UNIVERSE + default_endpoint = EchoClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EchoClient._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", [ + (EchoClient, transports.EchoGrpcTransport, "grpc"), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio"), + (EchoClient, transports.EchoRestTransport, "rest"), +]) +def test_echo_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", [ + (EchoClient, transports.EchoGrpcTransport, "grpc", grpc_helpers), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EchoClient, transports.EchoRestTransport, "rest", None), +]) +def test_echo_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_echo_client_client_options_from_dict(): + with mock.patch('google.showcase_v1beta1.services.echo.transports.EchoGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EchoClient( + 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", [ + (EchoClient, transports.EchoGrpcTransport, "grpc", grpc_helpers), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_echo_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( + "localhost:7469", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="localhost:7469", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + # Pure protobuf messages (non-proto-plus) require keyword arguments. + gs_echo.EchoRequest(**{ + "request_id": "explicit value for autopopulate-able field", + "other_request_id": "explicit value for autopopulate-able field", + }), + { + "request_id": "explicit value for autopopulate-able field", + "other_request_id": "explicit value for autopopulate-able field", + }, +]) +def test_echo(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + ) + response = client.echo(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.EchoRequest() + request.request_id = "explicit value for autopopulate-able field" + request.other_request_id = "explicit value for autopopulate-able field" + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoResponse) + assert response.content == 'content_value' + assert response.severity == gs_echo.Severity.NECESSARY + assert response.request_id == 'request_id_value' + assert response.other_request_id == 'other_request_id_value' + + +def test_echo_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 = EchoClient( + 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 = gs_echo.EchoRequest( + content='content_value', + header='header_value', + other_header='other_header_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.echo(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoRequest( + content='content_value', + header='header_value', + other_header='other_header_value', + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + +def test_echo_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 = EchoClient( + 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.echo 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.echo] = mock_rpc + request = {} + client.echo(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.echo(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_echo_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 = EchoAsyncClient( + 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.echo 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.echo] = mock_rpc + + request = {} + await client.echo(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.echo(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 +@pytest.mark.parametrize("request_type", [ + # Pure protobuf messages (non-proto-plus) require keyword arguments. + gs_echo.EchoRequest(**{ "request_id": "explicit value for autopopulate-able field", "other_request_id": "explicit value for autopopulate-able field", }), + { "request_id": "explicit value for autopopulate-able field", "other_request_id": "explicit value for autopopulate-able field", }, +]) +async def test_echo_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + response = await client.echo(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.EchoRequest() + request.request_id = "explicit value for autopopulate-able field" + request.other_request_id = "explicit value for autopopulate-able field" + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoResponse) + assert response.content == 'content_value' + assert response.severity == gs_echo.Severity.NECESSARY + assert response.request_id == 'request_id_value' + assert response.other_request_id == 'other_request_id_value' + + +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoErrorDetailsRequest(), + {}, +]) +def test_echo_error_details(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.echo_error_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.EchoErrorDetailsResponse( + ) + response = client.echo_error_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.EchoErrorDetailsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoErrorDetailsResponse) + + +def test_echo_error_details_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 = EchoClient( + 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 = gs_echo.EchoErrorDetailsRequest( + single_detail_text='single_detail_text_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.echo_error_details), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.echo_error_details(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoErrorDetailsRequest( + single_detail_text='single_detail_text_value', + ) + assert args[0] == request_msg + +def test_echo_error_details_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 = EchoClient( + 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.echo_error_details 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.echo_error_details] = mock_rpc + request = {} + client.echo_error_details(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.echo_error_details(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_echo_error_details_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 = EchoAsyncClient( + 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.echo_error_details 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.echo_error_details] = mock_rpc + + request = {} + await client.echo_error_details(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.echo_error_details(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoErrorDetailsRequest(), + {}, +]) +async def test_echo_error_details_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.echo_error_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoErrorDetailsResponse( + )) + response = await client.echo_error_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.EchoErrorDetailsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoErrorDetailsResponse) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.ExpandRequest(), + {}, +]) +def test_expand(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([gs_echo.EchoResponse()]) + response = client.expand(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.ExpandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, gs_echo.EchoResponse) + + +def test_expand_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 = EchoClient( + 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 = gs_echo.ExpandRequest( + content='content_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.expand(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.ExpandRequest( + content='content_value', + ) + assert args[0] == request_msg + +def test_expand_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 = EchoClient( + 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.expand 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.expand] = mock_rpc + request = {} + client.expand(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.expand(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_expand_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 = EchoAsyncClient( + 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.expand 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.expand] = mock_rpc + + request = {} + await client.expand(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.expand(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.ExpandRequest(), + {}, +]) +async def test_expand_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[gs_echo.EchoResponse()]) + response = await client.expand(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.ExpandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, gs_echo.EchoResponse) + + +def test_expand_flattened(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([gs_echo.EchoResponse()]) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.expand( + content='content_value', + error=status_pb2.Status(code=411), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].content + mock_val = 'content_value' + assert arg == mock_val + arg = args[0].error + mock_val = status_pb2.Status(code=411) + assert arg == mock_val + + +def test_expand_flattened_error(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.expand( + gs_echo.ExpandRequest(), + content='content_value', + error=status_pb2.Status(code=411), + ) + +@pytest.mark.asyncio +async def test_expand_flattened_async(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([gs_echo.EchoResponse()]) + + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.expand( + content='content_value', + error=status_pb2.Status(code=411), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].content + mock_val = 'content_value' + assert arg == mock_val + arg = args[0].error + mock_val = status_pb2.Status(code=411) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_expand_flattened_error_async(): + client = EchoAsyncClient( + 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.expand( + gs_echo.ExpandRequest(), + content='content_value', + error=status_pb2.Status(code=411), + ) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoRequest(), + {}, +]) +def test_collect(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + ) + response = client.collect(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoResponse) + assert response.content == 'content_value' + assert response.severity == gs_echo.Severity.NECESSARY + assert response.request_id == 'request_id_value' + assert response.other_request_id == 'other_request_id_value' + +def test_collect_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 = EchoClient( + 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.collect 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.collect] = mock_rpc + request = [{}] + client.collect(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.collect(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_collect_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 = EchoAsyncClient( + 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.collect 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.collect] = mock_rpc + + request = [{}] + await client.collect(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.collect(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoRequest(), + {}, +]) +async def test_collect_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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 + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeStreamUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + response = await (await client.collect(iter(requests))) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoResponse) + assert response.content == 'content_value' + assert response.severity == gs_echo.Severity.NECESSARY + assert response.request_id == 'request_id_value' + assert response.other_request_id == 'other_request_id_value' + + +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoRequest(), + {}, +]) +def test_chat(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.chat), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([gs_echo.EchoResponse()]) + response = client.chat(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, gs_echo.EchoResponse) + +def test_chat_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 = EchoClient( + 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.chat 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.chat] = mock_rpc + request = [{}] + client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.chat(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_chat_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 = EchoAsyncClient( + 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.chat 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.chat] = mock_rpc + + request = [{}] + await client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.chat(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoRequest(), + {}, +]) +async def test_chat_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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 + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.chat), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[gs_echo.EchoResponse()]) + response = await client.chat(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, gs_echo.EchoResponse) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandRequest(), + {}, +]) +def test_paged_expand(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + ) + response = client.paged_expand(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.PagedExpandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_paged_expand_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 = EchoClient( + 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 = gs_echo.PagedExpandRequest( + content='content_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.paged_expand), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.paged_expand(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest( + content='content_value', + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_paged_expand_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 = EchoClient( + 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.paged_expand 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.paged_expand] = mock_rpc + request = {} + client.paged_expand(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.paged_expand(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_paged_expand_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 = EchoAsyncClient( + 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.paged_expand 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.paged_expand] = mock_rpc + + request = {} + await client.paged_expand(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.paged_expand(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandRequest(), + {}, +]) +async def test_paged_expand_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.paged_expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + )) + response = await client.paged_expand(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.PagedExpandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_paged_expand_pager(transport_name: str = "grpc"): + client = EchoClient( + 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.paged_expand), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + if HAS_GOOGLE_API_CORE_VERSION_HEADER: + expected_metadata = tuple(expected_metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + pager = client.paged_expand(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gs_echo.EchoResponse) + for i in results) +def test_paged_expand_pages(transport_name: str = "grpc"): + client = EchoClient( + 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.paged_expand), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + pages = list(client.paged_expand(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_paged_expand_async_pager(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + async_pager = await client.paged_expand(request={},) + assert async_pager.next_page_token == 'abc' + assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, gs_echo.EchoResponse) + for i in responses) + + +@pytest.mark.asyncio +async def test_paged_expand_async_pages(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.paged_expand(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", [ + gs_echo.PagedExpandLegacyRequest(), + {}, +]) +def test_paged_expand_legacy(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + ) + response = client.paged_expand_legacy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.PagedExpandLegacyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandLegacyPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_paged_expand_legacy_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 = EchoClient( + 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 = gs_echo.PagedExpandLegacyRequest( + content='content_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.paged_expand_legacy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.paged_expand_legacy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandLegacyRequest( + content='content_value', + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_paged_expand_legacy_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 = EchoClient( + 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.paged_expand_legacy 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.paged_expand_legacy] = mock_rpc + request = {} + client.paged_expand_legacy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.paged_expand_legacy(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_paged_expand_legacy_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 = EchoAsyncClient( + 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.paged_expand_legacy 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.paged_expand_legacy] = mock_rpc + + request = {} + await client.paged_expand_legacy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.paged_expand_legacy(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandLegacyRequest(), + {}, +]) +async def test_paged_expand_legacy_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.paged_expand_legacy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + )) + response = await client.paged_expand_legacy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.PagedExpandLegacyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandLegacyAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_paged_expand_legacy_pager(transport_name: str = "grpc"): + client = EchoClient( + 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.paged_expand_legacy), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + if HAS_GOOGLE_API_CORE_VERSION_HEADER: + expected_metadata = tuple(expected_metadata) + ( + version_header.to_api_version_header("v1_20240408"), + ) + pager = client.paged_expand_legacy(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gs_echo.EchoResponse) + for i in results) +def test_paged_expand_legacy_pages(transport_name: str = "grpc"): + client = EchoClient( + 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.paged_expand_legacy), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + pages = list(client.paged_expand_legacy(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_paged_expand_legacy_async_pager(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + async_pager = await client.paged_expand_legacy(request={},) + assert async_pager.next_page_token == 'abc' + assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, gs_echo.EchoResponse) + for i in responses) + + +@pytest.mark.asyncio +async def test_paged_expand_legacy_async_pages(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.paged_expand_legacy(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", [ + gs_echo.PagedExpandRequest(), + {}, +]) +def test_paged_expand_legacy_mapped(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.PagedExpandLegacyMappedResponse( + next_page_token='next_page_token_value', + ) + response = client.paged_expand_legacy_mapped(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.PagedExpandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandLegacyMappedPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_paged_expand_legacy_mapped_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 = EchoClient( + 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 = gs_echo.PagedExpandRequest( + content='content_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.paged_expand_legacy_mapped), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.paged_expand_legacy_mapped(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest( + content='content_value', + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_paged_expand_legacy_mapped_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 = EchoClient( + 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.paged_expand_legacy_mapped 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.paged_expand_legacy_mapped] = mock_rpc + request = {} + client.paged_expand_legacy_mapped(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.paged_expand_legacy_mapped(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_paged_expand_legacy_mapped_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 = EchoAsyncClient( + 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.paged_expand_legacy_mapped 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.paged_expand_legacy_mapped] = mock_rpc + + request = {} + await client.paged_expand_legacy_mapped(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.paged_expand_legacy_mapped(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandRequest(), + {}, +]) +async def test_paged_expand_legacy_mapped_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.paged_expand_legacy_mapped), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandLegacyMappedResponse( + next_page_token='next_page_token_value', + )) + response = await client.paged_expand_legacy_mapped(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.PagedExpandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandLegacyMappedAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_paged_expand_legacy_mapped_pages(transport_name: str = "grpc"): + client = EchoClient( + 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.paged_expand_legacy_mapped), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'a':gs_echo.PagedExpandResponseList(), + 'b':gs_echo.PagedExpandResponseList(), + 'c':gs_echo.PagedExpandResponseList(), + }, + next_page_token='abc', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={}, + next_page_token='def', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'g':gs_echo.PagedExpandResponseList(), + }, + next_page_token='ghi', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'h':gs_echo.PagedExpandResponseList(), + 'i':gs_echo.PagedExpandResponseList(), + }, + ), + RuntimeError, + ) + pages = list(client.paged_expand_legacy_mapped(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_paged_expand_legacy_mapped_async_pager(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'a':gs_echo.PagedExpandResponseList(), + 'b':gs_echo.PagedExpandResponseList(), + 'c':gs_echo.PagedExpandResponseList(), + }, + next_page_token='abc', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={}, + next_page_token='def', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'g':gs_echo.PagedExpandResponseList(), + }, + next_page_token='ghi', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'h':gs_echo.PagedExpandResponseList(), + 'i':gs_echo.PagedExpandResponseList(), + }, + ), + RuntimeError, + ) + async_pager = await client.paged_expand_legacy_mapped(request={},) + assert async_pager.next_page_token == 'abc' + assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + + assert all( + isinstance(i, tuple) + for i in responses) + for result in responses: + assert isinstance(result, tuple) + assert tuple(type(t) for t in result) == (str, gs_echo.PagedExpandResponseList) + + assert async_pager.get('a') is None + assert isinstance(async_pager.get('h'), gs_echo.PagedExpandResponseList) + + +@pytest.mark.asyncio +async def test_paged_expand_legacy_mapped_async_pages(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'a':gs_echo.PagedExpandResponseList(), + 'b':gs_echo.PagedExpandResponseList(), + 'c':gs_echo.PagedExpandResponseList(), + }, + next_page_token='abc', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={}, + next_page_token='def', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'g':gs_echo.PagedExpandResponseList(), + }, + next_page_token='ghi', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'h':gs_echo.PagedExpandResponseList(), + 'i':gs_echo.PagedExpandResponseList(), + }, + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.paged_expand_legacy_mapped(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", [ + gs_echo.WaitRequest(), + {}, +]) +def test_wait(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.wait), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.wait(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.WaitRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_wait_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 = EchoClient( + 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 = gs_echo.WaitRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.wait), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.wait(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.WaitRequest( + ) + assert args[0] == request_msg + +def test_wait_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 = EchoClient( + 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.wait 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.wait] = mock_rpc + request = {} + client.wait(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.wait(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_wait_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 = EchoAsyncClient( + 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.wait 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.wait] = mock_rpc + + request = {} + await client.wait(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.wait(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.WaitRequest(), + {}, +]) +async def test_wait_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.wait), + '__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.wait(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.WaitRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.BlockRequest(), + {}, +]) +def test_block(request_type, transport: str = 'grpc'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.block), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gs_echo.BlockResponse( + content='content_value', + ) + response = client.block(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gs_echo.BlockRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.BlockResponse) + assert response.content == 'content_value' + + +def test_block_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 = EchoClient( + 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 = gs_echo.BlockRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.block), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.block(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.BlockRequest( + ) + assert args[0] == request_msg + +def test_block_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 = EchoClient( + 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.block 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.block] = mock_rpc + request = {} + client.block(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.block(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_block_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 = EchoAsyncClient( + 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.block 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.block] = mock_rpc + + request = {} + await client.block(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.block(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 +@pytest.mark.parametrize("request_type", [ + gs_echo.BlockRequest(), + {}, +]) +async def test_block_async(request_type, transport: str = 'grpc_asyncio'): + client = EchoAsyncClient( + 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.block), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.BlockResponse( + content='content_value', + )) + response = await client.block(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gs_echo.BlockRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.BlockResponse) + assert response.content == 'content_value' + + +def test_echo_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 = EchoClient( + 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.echo 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.echo] = mock_rpc + + request = {} + client.echo(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.echo(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_echo_error_details_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 = EchoClient( + 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.echo_error_details 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.echo_error_details] = mock_rpc + + request = {} + client.echo_error_details(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.echo_error_details(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_expand_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 = EchoClient( + 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.expand 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.expand] = mock_rpc + + request = {} + client.expand(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.expand(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_expand_rest_flattened(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.EchoResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + content='content_value', + error=status_pb2.Status(code=411), + ) + 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 = gs_echo.EchoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + client.expand(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/echo:expand" % client.transport._host, args[1]) + + +def test_expand_rest_flattened_error(transport: str = 'rest'): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.expand( + gs_echo.ExpandRequest(), + content='content_value', + error=status_pb2.Status(code=411), + ) + + +def test_collect_rest_unimplemented(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = gs_echo.EchoRequest() + requests = [request] + with pytest.raises(NotImplementedError): + client.collect(requests) + + +def test_chat_rest_no_http_options(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = gs_echo.EchoRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.chat(requests) + + +def test_paged_expand_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 = EchoClient( + 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.paged_expand 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.paged_expand] = mock_rpc + + request = {} + client.paged_expand(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.paged_expand(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_paged_expand_rest_required_fields(request_type=gs_echo.PagedExpandRequest): + transport_class = transports.EchoRestTransport + + request_init = {} + request_init["content"] = "" + 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()).paged_expand._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["content"] = 'content_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).paged_expand._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "content" in jsonified_request + assert jsonified_request["content"] == 'content_value' + + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gs_echo.PagedExpandResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gs_echo.PagedExpandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.paged_expand(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_paged_expand_rest_unset_required_fields(): + transport = transports.EchoRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.paged_expand._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("content", ))) + + +def test_paged_expand_rest_pager(transport: str = 'rest'): + client = EchoClient( + 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 = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gs_echo.PagedExpandResponse.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 = {} + + pager = client.paged_expand(request=sample_request) + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gs_echo.EchoResponse) + for i in results) + + pages = list(client.paged_expand(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_paged_expand_legacy_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 = EchoClient( + 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.paged_expand_legacy 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.paged_expand_legacy] = mock_rpc + + request = {} + client.paged_expand_legacy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.paged_expand_legacy(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_paged_expand_legacy_rest_required_fields(request_type=gs_echo.PagedExpandLegacyRequest): + transport_class = transports.EchoRestTransport + + request_init = {} + request_init["content"] = "" + 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()).paged_expand_legacy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["content"] = 'content_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).paged_expand_legacy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "content" in jsonified_request + assert jsonified_request["content"] == 'content_value' + + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gs_echo.PagedExpandResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gs_echo.PagedExpandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.paged_expand_legacy(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_paged_expand_legacy_rest_unset_required_fields(): + transport = transports.EchoRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.paged_expand_legacy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("content", ))) + + +def test_paged_expand_legacy_rest_pager(transport: str = 'rest'): + client = EchoClient( + 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 = ( + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + next_page_token='abc', + ), + gs_echo.PagedExpandResponse( + responses=[], + next_page_token='def', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + ], + next_page_token='ghi', + ), + gs_echo.PagedExpandResponse( + responses=[ + gs_echo.EchoResponse(), + gs_echo.EchoResponse(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gs_echo.PagedExpandResponse.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 = {} + + pager = client.paged_expand_legacy(request=sample_request) + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gs_echo.EchoResponse) + for i in results) + + pages = list(client.paged_expand_legacy(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_paged_expand_legacy_mapped_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 = EchoClient( + 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.paged_expand_legacy_mapped 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.paged_expand_legacy_mapped] = mock_rpc + + request = {} + client.paged_expand_legacy_mapped(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.paged_expand_legacy_mapped(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_paged_expand_legacy_mapped_rest_required_fields(request_type=gs_echo.PagedExpandRequest): + transport_class = transports.EchoRestTransport + + request_init = {} + request_init["content"] = "" + 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()).paged_expand_legacy_mapped._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["content"] = 'content_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).paged_expand_legacy_mapped._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "content" in jsonified_request + assert jsonified_request["content"] == 'content_value' + + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gs_echo.PagedExpandLegacyMappedResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gs_echo.PagedExpandLegacyMappedResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.paged_expand_legacy_mapped(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_paged_expand_legacy_mapped_rest_unset_required_fields(): + transport = transports.EchoRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.paged_expand_legacy_mapped._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("content", ))) + + +def test_paged_expand_legacy_mapped_rest_pager(transport: str = 'rest'): + client = EchoClient( + 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 = ( + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'a':gs_echo.PagedExpandResponseList(), + 'b':gs_echo.PagedExpandResponseList(), + 'c':gs_echo.PagedExpandResponseList(), + }, + next_page_token='abc', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={}, + next_page_token='def', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'g':gs_echo.PagedExpandResponseList(), + }, + next_page_token='ghi', + ), + gs_echo.PagedExpandLegacyMappedResponse( + alphabetized={ + 'h':gs_echo.PagedExpandResponseList(), + 'i':gs_echo.PagedExpandResponseList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gs_echo.PagedExpandLegacyMappedResponse.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 = {} + + pager = client.paged_expand_legacy_mapped(request=sample_request) + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + assert isinstance(pager.get('a'), gs_echo.PagedExpandResponseList) + assert pager.get('h') is None + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, tuple) + for i in results) + for result in results: + assert isinstance(result, tuple) + assert tuple(type(t) for t in result) == (str, gs_echo.PagedExpandResponseList) + + assert pager.get('a') is None + assert isinstance(pager.get('h'), gs_echo.PagedExpandResponseList) + + pages = list(client.paged_expand_legacy_mapped(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_wait_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 = EchoClient( + 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.wait 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.wait] = mock_rpc + + request = {} + client.wait(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.wait(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_block_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 = EchoClient( + 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.block 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.block] = mock_rpc + + request = {} + client.block(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.block(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_chat_rest_error(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.chat({}) + assert ( + "Method Chat is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EchoGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EchoGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EchoClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EchoGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EchoClient( + 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 = EchoClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EchoGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EchoClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EchoGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EchoClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EchoGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EchoGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EchoGrpcTransport, + transports.EchoGrpcAsyncIOTransport, + transports.EchoRestTransport, +]) +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 = EchoClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EchoClient( + 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_echo_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_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_echo_error_details_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo_error_details), + '__call__') as call: + call.return_value = gs_echo.EchoErrorDetailsResponse() + client.echo_error_details(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoErrorDetailsRequest() + assert args[0] == request_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_expand_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + call.return_value = iter([gs_echo.EchoResponse()]) + client.expand(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.ExpandRequest() + assert args[0] == request_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_paged_expand_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__') as call: + call.return_value = gs_echo.PagedExpandResponse() + client.paged_expand(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest() + assert args[0] == request_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_paged_expand_legacy_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__') as call: + call.return_value = gs_echo.PagedExpandResponse() + client.paged_expand_legacy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandLegacyRequest() + assert args[0] == request_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_paged_expand_legacy_mapped_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__') as call: + call.return_value = gs_echo.PagedExpandLegacyMappedResponse() + client.paged_expand_legacy_mapped(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest() + assert args[0] == request_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_wait_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.wait), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.wait(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.WaitRequest() + assert args[0] == request_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_block_empty_call_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.block), + '__call__') as call: + call.return_value = gs_echo.BlockResponse() + client.block(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.BlockRequest() + assert args[0] == request_msg + + +def test_echo_routing_parameters_request_1_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_2_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_3_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"header": "regions/sample1/zones/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "regions/sample1/zones/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'regions/sample1/zones/sample2/sample3', 'routing_id': 'regions/sample1/zones/sample2/sample3', 'table_name': 'regions/sample1/zones/sample2/sample3'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_4_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"header": "projects/sample1/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/sample2"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/sample2', 'routing_id': 'projects/sample1/sample2', 'super_id': 'projects/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_5_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_6_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_7_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"other_header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"other_header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'baz': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_8_grpc(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + call.return_value = gs_echo.EchoResponse() + client.echo(request={"other_header": "projects/sample1/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"other_header": "projects/sample1/sample2"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'baz': 'projects/sample1/sample2', 'qux': 'projects/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_grpc_asyncio(): + transport = EchoAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EchoAsyncClient( + 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_echo_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_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_echo_error_details_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo_error_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoErrorDetailsResponse( + )) + await client.echo_error_details(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoErrorDetailsRequest() + assert args[0] == request_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_expand_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[gs_echo.EchoResponse()]) + await client.expand(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.ExpandRequest() + assert args[0] == request_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_paged_expand_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + )) + await client.paged_expand(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest() + assert args[0] == request_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_paged_expand_legacy_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + )) + await client.paged_expand_legacy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandLegacyRequest() + assert args[0] == request_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_paged_expand_legacy_mapped_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandLegacyMappedResponse( + next_page_token='next_page_token_value', + )) + await client.paged_expand_legacy_mapped(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest() + assert args[0] == request_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_wait_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.wait), + '__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.wait(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.WaitRequest() + assert args[0] == request_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_block_empty_call_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.block), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.BlockResponse( + content='content_value', + )) + await client.block(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.BlockRequest() + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_1_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_2_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_3_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"header": "regions/sample1/zones/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "regions/sample1/zones/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'regions/sample1/zones/sample2/sample3', 'routing_id': 'regions/sample1/zones/sample2/sample3', 'table_name': 'regions/sample1/zones/sample2/sample3'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_4_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"header": "projects/sample1/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/sample2"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/sample2', 'routing_id': 'projects/sample1/sample2', 'super_id': 'projects/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_5_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_6_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_7_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"other_header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"other_header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'baz': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_echo_routing_parameters_request_8_grpc_asyncio(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_value', + )) + await client.echo(request={"other_header": "projects/sample1/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"other_header": "projects/sample1/sample2"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'baz': 'projects/sample1/sample2', 'qux': 'projects/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_rest(): + transport = EchoClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_echo_rest_bad_request(request_type=gs_echo.EchoRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.echo(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoRequest, + dict, +]) +def test_echo_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_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 = gs_echo.EchoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.echo(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoResponse) + assert response.content == 'content_value' + assert response.severity == gs_echo.Severity.NECESSARY + assert response.request_id == 'request_id_value' + assert response.other_request_id == 'other_request_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_echo_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_echo") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_echo_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_echo") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.EchoRequest.pb(gs_echo.EchoRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.EchoResponse.to_json(gs_echo.EchoResponse()) + req.return_value.content = return_value + + request = gs_echo.EchoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.EchoResponse() + post_with_metadata.return_value = gs_echo.EchoResponse(), metadata + + client.echo(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_echo_error_details_rest_bad_request(request_type=gs_echo.EchoErrorDetailsRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.echo_error_details(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.EchoErrorDetailsRequest, + dict, +]) +def test_echo_error_details_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.EchoErrorDetailsResponse( + ) + + # 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 = gs_echo.EchoErrorDetailsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.echo_error_details(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoErrorDetailsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_echo_error_details_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_echo_error_details") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_echo_error_details_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_echo_error_details") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.EchoErrorDetailsRequest.pb(gs_echo.EchoErrorDetailsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.EchoErrorDetailsResponse.to_json(gs_echo.EchoErrorDetailsResponse()) + req.return_value.content = return_value + + request = gs_echo.EchoErrorDetailsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.EchoErrorDetailsResponse() + post_with_metadata.return_value = gs_echo.EchoErrorDetailsResponse(), metadata + + client.echo_error_details(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_expand_rest_bad_request(request_type=gs_echo.ExpandRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.expand(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.ExpandRequest, + dict, +]) +def test_expand_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.EchoResponse( + content='content_value', + severity=gs_echo.Severity.NECESSARY, + request_id='request_id_value', + other_request_id='other_request_id_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 = gs_echo.EchoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.expand(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.EchoResponse) + assert response.content == 'content_value' + assert response.severity == gs_echo.Severity.NECESSARY + assert response.request_id == 'request_id_value' + assert response.other_request_id == 'other_request_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_expand_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_expand") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_expand_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_expand") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.ExpandRequest.pb(gs_echo.ExpandRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.EchoResponse.to_json(gs_echo.EchoResponse()) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = gs_echo.ExpandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.EchoResponse() + post_with_metadata.return_value = gs_echo.EchoResponse(), metadata + + client.expand(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_collect_rest_error(): + + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.collect({}) + assert ( + "Method Collect is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_chat_rest_error(): + + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.chat({}) + assert ( + "Method Chat is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_paged_expand_rest_bad_request(request_type=gs_echo.PagedExpandRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.paged_expand(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandRequest, + dict, +]) +def test_paged_expand_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gs_echo.PagedExpandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.paged_expand(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_paged_expand_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_paged_expand") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_paged_expand_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_paged_expand") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.PagedExpandRequest.pb(gs_echo.PagedExpandRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.PagedExpandResponse.to_json(gs_echo.PagedExpandResponse()) + req.return_value.content = return_value + + request = gs_echo.PagedExpandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.PagedExpandResponse() + post_with_metadata.return_value = gs_echo.PagedExpandResponse(), metadata + + client.paged_expand(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_paged_expand_legacy_rest_bad_request(request_type=gs_echo.PagedExpandLegacyRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.paged_expand_legacy(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandLegacyRequest, + dict, +]) +def test_paged_expand_legacy_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.PagedExpandResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gs_echo.PagedExpandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.paged_expand_legacy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandLegacyPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_paged_expand_legacy_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_paged_expand_legacy") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_paged_expand_legacy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_paged_expand_legacy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.PagedExpandLegacyRequest.pb(gs_echo.PagedExpandLegacyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.PagedExpandResponse.to_json(gs_echo.PagedExpandResponse()) + req.return_value.content = return_value + + request = gs_echo.PagedExpandLegacyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.PagedExpandResponse() + post_with_metadata.return_value = gs_echo.PagedExpandResponse(), metadata + + client.paged_expand_legacy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_paged_expand_legacy_mapped_rest_bad_request(request_type=gs_echo.PagedExpandRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.paged_expand_legacy_mapped(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.PagedExpandRequest, + dict, +]) +def test_paged_expand_legacy_mapped_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.PagedExpandLegacyMappedResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gs_echo.PagedExpandLegacyMappedResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.paged_expand_legacy_mapped(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PagedExpandLegacyMappedPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_paged_expand_legacy_mapped_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_paged_expand_legacy_mapped") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_paged_expand_legacy_mapped_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_paged_expand_legacy_mapped") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.PagedExpandRequest.pb(gs_echo.PagedExpandRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.PagedExpandLegacyMappedResponse.to_json(gs_echo.PagedExpandLegacyMappedResponse()) + req.return_value.content = return_value + + request = gs_echo.PagedExpandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.PagedExpandLegacyMappedResponse() + post_with_metadata.return_value = gs_echo.PagedExpandLegacyMappedResponse(), metadata + + client.paged_expand_legacy_mapped(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_wait_rest_bad_request(request_type=gs_echo.WaitRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.wait(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.WaitRequest, + dict, +]) +def test_wait_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.wait(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_wait_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_wait") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_wait_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_wait") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.WaitRequest.pb(gs_echo.WaitRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gs_echo.WaitRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.wait(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_block_rest_bad_request(request_type=gs_echo.BlockRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.block(request) + + +@pytest.mark.parametrize("request_type", [ + gs_echo.BlockRequest, + dict, +]) +def test_block_rest_call_success(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gs_echo.BlockResponse( + content='content_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 = gs_echo.BlockResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.block(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gs_echo.BlockResponse) + assert response.content == 'content_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_block_rest_interceptors(null_interceptor): + transport = transports.EchoRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EchoRestInterceptor(), + ) + client = EchoClient(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.EchoRestInterceptor, "post_block") as post, \ + mock.patch.object(transports.EchoRestInterceptor, "post_block_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EchoRestInterceptor, "pre_block") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gs_echo.BlockRequest.pb(gs_echo.BlockRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gs_echo.BlockResponse.to_json(gs_echo.BlockResponse()) + req.return_value.content = return_value + + request = gs_echo.BlockRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gs_echo.BlockResponse() + post_with_metadata.return_value = gs_echo.BlockResponse(), metadata + + client.block(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_initialize_client_w_rest(): + client = EchoClient( + 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_echo_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_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_echo_error_details_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo_error_details), + '__call__') as call: + client.echo_error_details(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.EchoErrorDetailsRequest() + assert args[0] == request_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_expand_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.expand), + '__call__') as call: + client.expand(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.ExpandRequest() + assert args[0] == request_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_paged_expand_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand), + '__call__') as call: + client.paged_expand(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest() + assert args[0] == request_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_paged_expand_legacy_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy), + '__call__') as call: + client.paged_expand_legacy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandLegacyRequest() + assert args[0] == request_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_paged_expand_legacy_mapped_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.paged_expand_legacy_mapped), + '__call__') as call: + client.paged_expand_legacy_mapped(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.PagedExpandRequest() + assert args[0] == request_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_wait_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.wait), + '__call__') as call: + client.wait(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.WaitRequest() + assert args[0] == request_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_block_empty_call_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.block), + '__call__') as call: + client.block(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gs_echo.BlockRequest() + assert args[0] == request_msg + + +def test_echo_routing_parameters_request_1_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_2_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_3_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"header": "regions/sample1/zones/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "regions/sample1/zones/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'regions/sample1/zones/sample2/sample3', 'routing_id': 'regions/sample1/zones/sample2/sample3', 'table_name': 'regions/sample1/zones/sample2/sample3'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_4_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"header": "projects/sample1/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/sample2"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/sample2', 'routing_id': 'projects/sample1/sample2', 'super_id': 'projects/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_5_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_6_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_7_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"other_header": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"other_header": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'baz': 'sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_echo_routing_parameters_request_8_rest(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.echo), + '__call__') as call: + client.echo(request={"other_header": "projects/sample1/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gs_echo.EchoRequest(**{"other_header": "projects/sample1/sample2"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].other_request_id) + request_msg.other_request_id = args[0].other_request_id + assert args[0] == request_msg + + expected_headers = {'baz': 'projects/sample1/sample2', 'qux': 'projects/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_echo_rest_lro_client(): + client = EchoClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EchoGrpcTransport, + ) + +def test_echo_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EchoTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_echo_base_transport(): + # Instantiate the base transport. + with mock.patch('google.showcase_v1beta1.services.echo.transports.EchoTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EchoTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'echo', + 'echo_error_details', + 'expand', + 'collect', + 'chat', + 'paged_expand', + 'paged_expand_legacy', + 'paged_expand_legacy_mapped', + 'wait', + 'block', + '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_echo_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.showcase_v1beta1.services.echo.transports.EchoTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EchoTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_echo_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.showcase_v1beta1.services.echo.transports.EchoTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EchoTransport() + adc.assert_called_once() + + +def test_echo_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) + EchoClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EchoGrpcTransport, + transports.EchoGrpcAsyncIOTransport, + ], +) +def test_echo_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EchoGrpcTransport, + transports.EchoGrpcAsyncIOTransport, + transports.EchoRestTransport, + ], +) +def test_echo_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.EchoGrpcTransport, grpc_helpers), + (transports.EchoGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_echo_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( + "localhost:7469", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="localhost:7469", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EchoGrpcTransport, transports.EchoGrpcAsyncIOTransport]) +def test_echo_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_echo_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.EchoRestTransport ( + 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_echo_host_no_port(transport_name): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='localhost'), + transport=transport_name, + ) + assert client.transport._host == ( + 'localhost:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://localhost' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_echo_host_with_port(transport_name): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='localhost:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'localhost:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://localhost:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_echo_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EchoClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EchoClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.echo._session + session2 = client2.transport.echo._session + assert session1 != session2 + session1 = client1.transport.echo_error_details._session + session2 = client2.transport.echo_error_details._session + assert session1 != session2 + session1 = client1.transport.expand._session + session2 = client2.transport.expand._session + assert session1 != session2 + session1 = client1.transport.collect._session + session2 = client2.transport.collect._session + assert session1 != session2 + session1 = client1.transport.chat._session + session2 = client2.transport.chat._session + assert session1 != session2 + session1 = client1.transport.paged_expand._session + session2 = client2.transport.paged_expand._session + assert session1 != session2 + session1 = client1.transport.paged_expand_legacy._session + session2 = client2.transport.paged_expand_legacy._session + assert session1 != session2 + session1 = client1.transport.paged_expand_legacy_mapped._session + session2 = client2.transport.paged_expand_legacy_mapped._session + assert session1 != session2 + session1 = client1.transport.wait._session + session2 = client2.transport.wait._session + assert session1 != session2 + session1 = client1.transport.block._session + session2 = client2.transport.block._session + assert session1 != session2 +def test_echo_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EchoGrpcTransport( + 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_echo_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EchoGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("transport_class", [transports.EchoGrpcTransport, transports.EchoGrpcAsyncIOTransport]) +def test_echo_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.EchoGrpcTransport, transports.EchoGrpcAsyncIOTransport]) +def test_echo_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_echo_grpc_lro_client(): + client = EchoClient( + 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_echo_grpc_lro_async_client(): + client = EchoAsyncClient( + 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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EchoClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = EchoClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EchoClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = EchoClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = EchoClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EchoClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EchoClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = EchoClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EchoClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = EchoClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = EchoClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EchoClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EchoClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = EchoClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EchoClient.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.EchoTransport, '_prep_wrapped_messages') as prep: + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EchoTransport, '_prep_wrapped_messages') as prep: + transport_class = EchoClient.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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_delete_operation_flattened(): + client = EchoClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = EchoAsyncClient( + 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 + ) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_cancel_operation_flattened(): + client = EchoClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = EchoAsyncClient( + 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 + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_get_operation_flattened(): + client = EchoClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = EchoAsyncClient( + 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() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_operations_flattened(): + client = EchoClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = EchoAsyncClient( + 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_list_locations_flattened(): + client = EchoClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = EchoAsyncClient( + 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() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_get_location_flattened(): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = EchoAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_set_iam_policy_flattened(): + client = EchoClient( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = EchoAsyncClient( + 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() + ) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +def test_get_iam_policy(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_get_iam_policy_flattened(): + client = EchoClient( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = EchoAsyncClient( + 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() + ) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +def test_test_iam_permissions(transport: str = "grpc"): + client = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EchoAsyncClient( + 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 = EchoClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoAsyncClient( + 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_test_iam_permissions_flattened(): + client = EchoClient( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = EchoAsyncClient( + 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() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = EchoClient( + 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 = EchoAsyncClient( + 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 = EchoClient( + 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 = EchoClient( + 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", [ + (EchoClient, transports.EchoGrpcTransport), + (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport), +]) +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/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py new file mode 100644 index 000000000000..7e61c0e1393d --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py @@ -0,0 +1,6950 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 asyncio +import re +from unittest import mock +from unittest.mock import AsyncMock + +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 collections.abc import Sequence, Mapping +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 gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.showcase_v1beta1.services.identity import IdentityAsyncClient +from google.showcase_v1beta1.services.identity import IdentityClient +from google.showcase_v1beta1.services.identity import pagers +from google.showcase_v1beta1.services.identity import transports +from google.showcase_v1beta1.types import identity +import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) +_UUID4_RE = re.compile(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}") + + +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 + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert IdentityClient._get_default_mtls_endpoint(None) is None + assert IdentityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert IdentityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert IdentityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert IdentityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert IdentityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert IdentityClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + +def test__read_environment_variables(): + assert IdentityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert IdentityClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert IdentityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + IdentityClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert IdentityClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert IdentityClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert IdentityClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert IdentityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + IdentityClient._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 IdentityClient._read_environment_variables() == (False, "auto", "foo.com") + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): + assert IdentityClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): + assert IdentityClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert IdentityClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert IdentityClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert IdentityClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): + assert IdentityClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert IdentityClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): + assert IdentityClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert IdentityClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + with pytest.raises(ValueError): + IdentityClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + assert IdentityClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert IdentityClient._use_client_cert_effective() is False + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert IdentityClient._get_client_cert_source(None, False) is None + assert IdentityClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert IdentityClient._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 IdentityClient._get_client_cert_source(None, True) is mock_default_cert_source + assert IdentityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) +@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = IdentityClient._DEFAULT_UNIVERSE + default_endpoint = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert IdentityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert IdentityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == IdentityClient.DEFAULT_MTLS_ENDPOINT + assert IdentityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert IdentityClient._get_api_endpoint(None, None, default_universe, "always") == IdentityClient.DEFAULT_MTLS_ENDPOINT + assert IdentityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == IdentityClient.DEFAULT_MTLS_ENDPOINT + assert IdentityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert IdentityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + IdentityClient._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 IdentityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert IdentityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert IdentityClient._get_universe_domain(None, None) == IdentityClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + IdentityClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = IdentityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = IdentityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +def test__setup_request_id(): + class MockRequest: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + def __contains__(self, key): + return hasattr(self, key) + + class MockProtoRequest: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + def HasField(self, key): + return hasattr(self, key) + + # Test with proto3 optional field not in request + request = MockRequest() + IdentityClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with proto3 optional field already in request + request = MockRequest(request_id="already_set") + IdentityClient._setup_request_id(request, "request_id", True) + assert request.request_id == "already_set" + + # Test with non-proto3 optional field empty + request = MockRequest(request_id="") + IdentityClient._setup_request_id(request, "request_id", False) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with non-proto3 optional field already set + request = MockRequest(request_id="already_set") + IdentityClient._setup_request_id(request, "request_id", False) + assert request.request_id == "already_set" + + # Test with proto3 optional field not in request (MockProtoRequest) + request = MockProtoRequest() + IdentityClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with proto3 optional field already in request (MockProtoRequest) + request = MockProtoRequest(request_id="already_set") + IdentityClient._setup_request_id(request, "request_id", True) + assert request.request_id == "already_set" + + # Test with ValueError + class MockValueErrorRequest: + def HasField(self, key): + raise ValueError("Mismatched field") + def __contains__(self, key): + return hasattr(self, key) + + request = MockValueErrorRequest() + IdentityClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with dict and proto3 optional field not in request + request = {} + IdentityClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) + + # Test with dict and proto3 optional field already in request + request = {"request_id": "already_set"} + IdentityClient._setup_request_id(request, "request_id", True) + assert request["request_id"] == "already_set" + + # Test with dict and non-proto3 optional field empty + request = {"request_id": ""} + IdentityClient._setup_request_id(request, "request_id", False) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) + + # Test with dict and non-proto3 optional field already set + request = {"request_id": "already_set"} + IdentityClient._setup_request_id(request, "request_id", False) + assert request["request_id"] == "already_set" + +@pytest.mark.parametrize("client_class,transport_name", [ + (IdentityClient, "grpc"), + (IdentityAsyncClient, "grpc_asyncio"), + (IdentityClient, "rest"), +]) +def test_identity_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 == ( + 'localhost:7469' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://localhost:7469' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.IdentityGrpcTransport, "grpc"), + (transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.IdentityRestTransport, "rest"), +]) +def test_identity_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", [ + (IdentityClient, "grpc"), + (IdentityAsyncClient, "grpc_asyncio"), + (IdentityClient, "rest"), +]) +def test_identity_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 == ( + 'localhost:7469' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://localhost:7469' + ) + + +def test_identity_client_get_transport_class(): + transport = IdentityClient.get_transport_class() + available_transports = [ + transports.IdentityGrpcTransport, + transports.IdentityRestTransport, + ] + assert transport in available_transports + + transport = IdentityClient.get_transport_class("grpc") + assert transport == transports.IdentityGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IdentityClient, transports.IdentityGrpcTransport, "grpc"), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio"), + (IdentityClient, transports.IdentityRestTransport, "rest"), +]) +@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) +@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) +def test_identity_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(IdentityClient, '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(IdentityClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (IdentityClient, transports.IdentityGrpcTransport, "grpc", "true"), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IdentityClient, transports.IdentityGrpcTransport, "grpc", "false"), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (IdentityClient, transports.IdentityRestTransport, "rest", "true"), + (IdentityClient, transports.IdentityRestTransport, "rest", "false"), +]) +@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) +@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_identity_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", [ + IdentityClient, IdentityAsyncClient +]) +@mock.patch.object(IdentityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IdentityClient)) +@mock.patch.object(IdentityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IdentityAsyncClient)) +def test_identity_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + +@pytest.mark.parametrize("client_class", [ + IdentityClient, IdentityAsyncClient +]) +@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) +@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) +def test_identity_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = IdentityClient._DEFAULT_UNIVERSE + default_endpoint = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = IdentityClient._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", [ + (IdentityClient, transports.IdentityGrpcTransport, "grpc"), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio"), + (IdentityClient, transports.IdentityRestTransport, "rest"), +]) +def test_identity_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", [ + (IdentityClient, transports.IdentityGrpcTransport, "grpc", grpc_helpers), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (IdentityClient, transports.IdentityRestTransport, "rest", None), +]) +def test_identity_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_identity_client_client_options_from_dict(): + with mock.patch('google.showcase_v1beta1.services.identity.transports.IdentityGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = IdentityClient( + 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", [ + (IdentityClient, transports.IdentityGrpcTransport, "grpc", grpc_helpers), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_identity_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( + "localhost:7469", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="localhost:7469", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + identity.CreateUserRequest(), + {}, +]) +def test_create_user(request_type, transport: str = 'grpc'): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + ) + response = client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = identity.CreateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +def test_create_user_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 = IdentityClient( + 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 = identity.CreateUserRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.CreateUserRequest( + ) + assert args[0] == request_msg + +def test_create_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + request = {} + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user(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_user_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 = IdentityAsyncClient( + 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_user 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_user] = mock_rpc + + request = {} + await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user(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 +@pytest.mark.parametrize("request_type", [ + identity.CreateUserRequest(), + {}, +]) +async def test_create_user_async(request_type, transport: str = 'grpc_asyncio'): + client = IdentityAsyncClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + )) + response = await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = identity.CreateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +def test_create_user_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user( + display_name='display_name_value', + email='email_value', + age=301, + nickname='nickname_value', + enable_notifications=True, + height_feet=0.1148, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].user.display_name + mock_val = 'display_name_value' + assert arg == mock_val + arg = args[0].user.email + mock_val = 'email_value' + assert arg == mock_val + arg = args[0].user.age + mock_val = 301 + assert arg == mock_val + arg = args[0].user.nickname + mock_val = 'nickname_value' + assert arg == mock_val + arg = args[0].user.enable_notifications + mock_val = True + assert arg == mock_val + arg = args[0].user.height_feet + mock_val = 0.1148 + assert arg == mock_val + + +def test_create_user_flattened_error(): + client = IdentityClient( + credentials=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_user( + identity.CreateUserRequest(), + display_name='display_name_value', + email='email_value', + age=301, + nickname='nickname_value', + enable_notifications=True, + height_feet=0.1148, + ) + +@pytest.mark.asyncio +async def test_create_user_flattened_async(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user( + display_name='display_name_value', + email='email_value', + age=301, + nickname='nickname_value', + enable_notifications=True, + height_feet=0.1148, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].user.display_name + mock_val = 'display_name_value' + assert arg == mock_val + arg = args[0].user.email + mock_val = 'email_value' + assert arg == mock_val + arg = args[0].user.age + mock_val = 301 + assert arg == mock_val + arg = args[0].user.nickname + mock_val = 'nickname_value' + assert arg == mock_val + arg = args[0].user.enable_notifications + mock_val = True + assert arg == mock_val + arg = args[0].user.height_feet + mock_val = 0.1148 + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_flattened_error_async(): + client = IdentityAsyncClient( + 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_user( + identity.CreateUserRequest(), + display_name='display_name_value', + email='email_value', + age=301, + nickname='nickname_value', + enable_notifications=True, + height_feet=0.1148, + ) + + +@pytest.mark.parametrize("request_type", [ + identity.GetUserRequest(), + {}, +]) +def test_get_user(request_type, transport: str = 'grpc'): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = identity.GetUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +def test_get_user_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 = IdentityClient( + 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 = identity.GetUserRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.GetUserRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_get_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + request = {} + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user(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_user_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 = IdentityAsyncClient( + 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_user 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_user] = mock_rpc + + request = {} + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user(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 +@pytest.mark.parametrize("request_type", [ + identity.GetUserRequest(), + {}, +]) +async def test_get_user_async(request_type, transport: str = 'grpc_asyncio'): + client = IdentityAsyncClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + )) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = identity.GetUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + +def test_get_user_field_headers(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = identity.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = identity.User() + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_user_field_headers_async(): + client = IdentityAsyncClient( + 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 = identity.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_user_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user( + name='name_value', + ) + + # Establish that the 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_user_flattened_error(): + client = IdentityClient( + credentials=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_user( + identity.GetUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_flattened_async(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user( + name='name_value', + ) + + # Establish that 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_user_flattened_error_async(): + client = IdentityAsyncClient( + 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_user( + identity.GetUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + identity.UpdateUserRequest(), + {}, +]) +def test_update_user(request_type, transport: str = 'grpc'): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + ) + response = client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = identity.UpdateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +def test_update_user_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 = IdentityClient( + 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 = identity.UpdateUserRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.UpdateUserRequest( + ) + assert args[0] == request_msg + +def test_update_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + request = {} + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user(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_user_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 = IdentityAsyncClient( + 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_user 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_user] = mock_rpc + + request = {} + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user(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 +@pytest.mark.parametrize("request_type", [ + identity.UpdateUserRequest(), + {}, +]) +async def test_update_user_async(request_type, transport: str = 'grpc_asyncio'): + client = IdentityAsyncClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + )) + response = await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = identity.UpdateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + +def test_update_user_field_headers(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = identity.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = identity.User() + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = IdentityAsyncClient( + 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 = identity.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + identity.DeleteUserRequest(), + {}, +]) +def test_delete_user(request_type, transport: str = 'grpc'): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = identity.DeleteUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_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 = IdentityClient( + 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 = identity.DeleteUserRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.DeleteUserRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_delete_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(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_user_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 = IdentityAsyncClient( + 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_user 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_user] = mock_rpc + + request = {} + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user(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 +@pytest.mark.parametrize("request_type", [ + identity.DeleteUserRequest(), + {}, +]) +async def test_delete_user_async(request_type, transport: str = 'grpc_asyncio'): + client = IdentityAsyncClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = identity.DeleteUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_user_field_headers(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = identity.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_user_field_headers_async(): + client = IdentityAsyncClient( + 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 = identity.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_user_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user( + name='name_value', + ) + + # Establish that the 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_user_flattened_error(): + client = IdentityClient( + credentials=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_user( + identity.DeleteUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user( + name='name_value', + ) + + # Establish that 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_user_flattened_error_async(): + client = IdentityAsyncClient( + 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_user( + identity.DeleteUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + identity.ListUsersRequest(), + {}, +]) +def test_list_users(request_type, transport: str = 'grpc'): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = identity.ListUsersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = identity.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_users_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 = IdentityClient( + 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 = identity.ListUsersRequest( + 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_users), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_users(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.ListUsersRequest( + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_list_users_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 = IdentityClient( + 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_users 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_users] = mock_rpc + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_users(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_users_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 = IdentityAsyncClient( + 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_users 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_users] = mock_rpc + + request = {} + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_users(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 +@pytest.mark.parametrize("request_type", [ + identity.ListUsersRequest(), + {}, +]) +async def test_list_users_async(request_type, transport: str = 'grpc_asyncio'): + client = IdentityAsyncClient( + 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.ListUsersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = identity.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_users_pager(transport_name: str = "grpc"): + client = IdentityClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + identity.User(), + ], + next_page_token='abc', + ), + identity.ListUsersResponse( + users=[], + next_page_token='def', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + ], + next_page_token='ghi', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_users(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, identity.User) + for i in results) +def test_list_users_pages(transport_name: str = "grpc"): + client = IdentityClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + identity.User(), + ], + next_page_token='abc', + ), + identity.ListUsersResponse( + users=[], + next_page_token='def', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + ], + next_page_token='ghi', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_users_async_pager(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + identity.User(), + ], + next_page_token='abc', + ), + identity.ListUsersResponse( + users=[], + next_page_token='def', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + ], + next_page_token='ghi', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users(request={},) + assert async_pager.next_page_token == 'abc' + assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, identity.User) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + identity.User(), + ], + next_page_token='abc', + ), + identity.ListUsersResponse( + users=[], + next_page_token='def', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + ], + next_page_token='ghi', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + + request = {} + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user(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_user_rest_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = identity.User() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + display_name='display_name_value', + email='email_value', + age=301, + nickname='nickname_value', + enable_notifications=True, + height_feet=0.1148, + ) + 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 = identity.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_user(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/users" % client.transport._host, args[1]) + + +def test_create_user_rest_flattened_error(transport: str = 'rest'): + client = IdentityClient( + credentials=ga_credentials.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_user( + identity.CreateUserRequest(), + display_name='display_name_value', + email='email_value', + age=301, + nickname='nickname_value', + enable_notifications=True, + height_feet=0.1148, + ) + + +def test_get_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + + request = {} + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user(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_user_rest_required_fields(request_type=identity.GetUserRequest): + transport_class = transports.IdentityRestTransport + + 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_user._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_user._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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = identity.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = identity.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_user(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_user_rest_unset_required_fields(): + transport = transports.IdentityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_rest_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = identity.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'users/sample1'} + + # 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 = identity.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_user(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=users/*}" % client.transport._host, args[1]) + + +def test_get_user_rest_flattened_error(transport: str = 'rest'): + client = IdentityClient( + credentials=ga_credentials.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_user( + identity.GetUserRequest(), + name='name_value', + ) + + +def test_update_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + + request = {} + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user(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_user_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 = IdentityClient( + 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_user 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_user] = mock_rpc + + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(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_user_rest_required_fields(request_type=identity.DeleteUserRequest): + transport_class = transports.IdentityRestTransport + + 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_user._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_user._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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_user(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_user_rest_unset_required_fields(): + transport = transports.IdentityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_rest_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'users/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_user(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=users/*}" % client.transport._host, args[1]) + + +def test_delete_user_rest_flattened_error(transport: str = 'rest'): + client = IdentityClient( + credentials=ga_credentials.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_user( + identity.DeleteUserRequest(), + name='name_value', + ) + + +def test_list_users_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 = IdentityClient( + 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_users 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_users] = mock_rpc + + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_users(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_users_rest_pager(transport: str = 'rest'): + client = IdentityClient( + 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 = ( + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + identity.User(), + ], + next_page_token='abc', + ), + identity.ListUsersResponse( + users=[], + next_page_token='def', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + ], + next_page_token='ghi', + ), + identity.ListUsersResponse( + users=[ + identity.User(), + identity.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(identity.ListUsersResponse.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 = {} + + pager = client.list_users(request=sample_request) + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, identity.User) + for i in results) + + pages = list(client.list_users(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.IdentityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.IdentityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IdentityClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.IdentityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = IdentityClient( + 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 = IdentityClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.IdentityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IdentityClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.IdentityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = IdentityClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.IdentityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.IdentityGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.IdentityGrpcTransport, + transports.IdentityGrpcAsyncIOTransport, + transports.IdentityRestTransport, +]) +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 = IdentityClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_user_empty_call_grpc(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = identity.User() + client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.CreateUserRequest() + assert args[0] == request_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_user_empty_call_grpc(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = identity.User() + client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.GetUserRequest() + assert args[0] == request_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_user_empty_call_grpc(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = identity.User() + client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.UpdateUserRequest() + assert args[0] == request_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_user_empty_call_grpc(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.DeleteUserRequest() + assert args[0] == request_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_users_empty_call_grpc(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = identity.ListUsersResponse() + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.ListUsersRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = IdentityAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_user_empty_call_grpc_asyncio(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + )) + await client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.CreateUserRequest() + assert args[0] == request_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_user_empty_call_grpc_asyncio(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + )) + await client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.GetUserRequest() + assert args[0] == request_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_user_empty_call_grpc_asyncio(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + )) + await client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.UpdateUserRequest() + assert args[0] == request_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_user_empty_call_grpc_asyncio(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.DeleteUserRequest() + assert args[0] == request_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_users_empty_call_grpc_asyncio(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.ListUsersResponse( + next_page_token='next_page_token_value', + )) + await client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.ListUsersRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = IdentityClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_user_rest_bad_request(request_type=identity.CreateUserRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_user(request) + + +@pytest.mark.parametrize("request_type", [ + identity.CreateUserRequest, + dict, +]) +def test_create_user_rest_call_success(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + ) + + # 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 = identity.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_rest_interceptors(null_interceptor): + transport = transports.IdentityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), + ) + client = IdentityClient(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.IdentityRestInterceptor, "post_create_user") as post, \ + mock.patch.object(transports.IdentityRestInterceptor, "post_create_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IdentityRestInterceptor, "pre_create_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = identity.CreateUserRequest.pb(identity.CreateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = identity.User.to_json(identity.User()) + req.return_value.content = return_value + + request = identity.CreateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = identity.User() + post_with_metadata.return_value = identity.User(), metadata + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_user_rest_bad_request(request_type=identity.GetUserRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_user(request) + + +@pytest.mark.parametrize("request_type", [ + identity.GetUserRequest, + dict, +]) +def test_get_user_rest_call_success(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + ) + + # 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 = identity.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_rest_interceptors(null_interceptor): + transport = transports.IdentityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), + ) + client = IdentityClient(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.IdentityRestInterceptor, "post_get_user") as post, \ + mock.patch.object(transports.IdentityRestInterceptor, "post_get_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IdentityRestInterceptor, "pre_get_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = identity.GetUserRequest.pb(identity.GetUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = identity.User.to_json(identity.User()) + req.return_value.content = return_value + + request = identity.GetUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = identity.User() + post_with_metadata.return_value = identity.User(), metadata + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_user_rest_bad_request(request_type=identity.UpdateUserRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'users/sample1'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_user(request) + + +@pytest.mark.parametrize("request_type", [ + identity.UpdateUserRequest, + dict, +]) +def test_update_user_rest_call_success(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'users/sample1'}} + request_init["user"] = {'name': 'users/sample1', 'display_name': 'display_name_value', 'email': 'email_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'age': 301, 'height_feet': 0.1148, 'nickname': 'nickname_value', 'enable_notifications': 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 = identity.UpdateUserRequest.meta.fields["user"] + + 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["user"].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["user"][field])): + del request_init["user"][field][i][subfield] + else: + del request_init["user"][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 = identity.User( + name='name_value', + display_name='display_name_value', + email='email_value', + age=301, + height_feet=0.1148, + nickname='nickname_value', + enable_notifications=True, + ) + + # 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 = identity.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, identity.User) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.email == 'email_value' + assert response.age == 301 + assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) + assert response.nickname == 'nickname_value' + assert response.enable_notifications is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_rest_interceptors(null_interceptor): + transport = transports.IdentityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), + ) + client = IdentityClient(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.IdentityRestInterceptor, "post_update_user") as post, \ + mock.patch.object(transports.IdentityRestInterceptor, "post_update_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IdentityRestInterceptor, "pre_update_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = identity.UpdateUserRequest.pb(identity.UpdateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = identity.User.to_json(identity.User()) + req.return_value.content = return_value + + request = identity.UpdateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = identity.User() + post_with_metadata.return_value = identity.User(), metadata + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_rest_bad_request(request_type=identity.DeleteUserRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_user(request) + + +@pytest.mark.parametrize("request_type", [ + identity.DeleteUserRequest, + dict, +]) +def test_delete_user_rest_call_success(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_user(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_rest_interceptors(null_interceptor): + transport = transports.IdentityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), + ) + client = IdentityClient(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.IdentityRestInterceptor, "pre_delete_user") as pre: + pre.assert_not_called() + pb_message = identity.DeleteUserRequest.pb(identity.DeleteUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = identity.DeleteUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_users_rest_bad_request(request_type=identity.ListUsersRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_users(request) + + +@pytest.mark.parametrize("request_type", [ + identity.ListUsersRequest, + dict, +]) +def test_list_users_rest_call_success(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = identity.ListUsersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = identity.ListUsersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_users_rest_interceptors(null_interceptor): + transport = transports.IdentityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), + ) + client = IdentityClient(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.IdentityRestInterceptor, "post_list_users") as post, \ + mock.patch.object(transports.IdentityRestInterceptor, "post_list_users_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IdentityRestInterceptor, "pre_list_users") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = identity.ListUsersRequest.pb(identity.ListUsersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = identity.ListUsersResponse.to_json(identity.ListUsersResponse()) + req.return_value.content = return_value + + request = identity.ListUsersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = identity.ListUsersResponse() + post_with_metadata.return_value = identity.ListUsersResponse(), metadata + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_initialize_client_w_rest(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_user_empty_call_rest(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.CreateUserRequest() + assert args[0] == request_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_user_empty_call_rest(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.GetUserRequest() + assert args[0] == request_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_user_empty_call_rest(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.UpdateUserRequest() + assert args[0] == request_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_user_empty_call_rest(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.DeleteUserRequest() + assert args[0] == request_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_users_empty_call_rest(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = identity.ListUsersRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.IdentityGrpcTransport, + ) + +def test_identity_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.IdentityTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_identity_base_transport(): + # Instantiate the base transport. + with mock.patch('google.showcase_v1beta1.services.identity.transports.IdentityTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.IdentityTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_user', + 'get_user', + 'update_user', + 'delete_user', + 'list_users', + '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() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_identity_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.showcase_v1beta1.services.identity.transports.IdentityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IdentityTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_identity_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.showcase_v1beta1.services.identity.transports.IdentityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IdentityTransport() + adc.assert_called_once() + + +def test_identity_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) + IdentityClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IdentityGrpcTransport, + transports.IdentityGrpcAsyncIOTransport, + ], +) +def test_identity_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IdentityGrpcTransport, + transports.IdentityGrpcAsyncIOTransport, + transports.IdentityRestTransport, + ], +) +def test_identity_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.IdentityGrpcTransport, grpc_helpers), + (transports.IdentityGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_identity_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( + "localhost:7469", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="localhost:7469", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.IdentityGrpcTransport, transports.IdentityGrpcAsyncIOTransport]) +def test_identity_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_identity_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.IdentityRestTransport ( + 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_identity_host_no_port(transport_name): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='localhost'), + transport=transport_name, + ) + assert client.transport._host == ( + 'localhost:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://localhost' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_identity_host_with_port(transport_name): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='localhost:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'localhost:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://localhost:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_identity_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = IdentityClient( + credentials=creds1, + transport=transport_name, + ) + client2 = IdentityClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_user._session + session2 = client2.transport.create_user._session + assert session1 != session2 + session1 = client1.transport.get_user._session + session2 = client2.transport.get_user._session + assert session1 != session2 + session1 = client1.transport.update_user._session + session2 = client2.transport.update_user._session + assert session1 != session2 + session1 = client1.transport.delete_user._session + session2 = client2.transport.delete_user._session + assert session1 != session2 + session1 = client1.transport.list_users._session + session2 = client2.transport.list_users._session + assert session1 != session2 +def test_identity_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IdentityGrpcTransport( + 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_identity_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IdentityGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("transport_class", [transports.IdentityGrpcTransport, transports.IdentityGrpcAsyncIOTransport]) +def test_identity_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.IdentityGrpcTransport, transports.IdentityGrpcAsyncIOTransport]) +def test_identity_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_user_path(): + user = "squid" + expected = "users/{user}".format(user=user, ) + actual = IdentityClient.user_path(user) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "user": "clam", + } + path = IdentityClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = IdentityClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = IdentityClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = IdentityClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = IdentityClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = IdentityClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = IdentityClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = IdentityClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = IdentityClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = IdentityClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = IdentityClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = IdentityClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = IdentityClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = IdentityClient.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 = IdentityClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = IdentityClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = IdentityClient.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.IdentityTransport, '_prep_wrapped_messages') as prep: + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.IdentityTransport, '_prep_wrapped_messages') as prep: + transport_class = IdentityClient.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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_delete_operation_flattened(): + client = IdentityClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = IdentityAsyncClient( + 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 + ) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_cancel_operation_flattened(): + client = IdentityClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = IdentityAsyncClient( + 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 + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_get_operation_flattened(): + client = IdentityClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = IdentityAsyncClient( + 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() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_operations_flattened(): + client = IdentityClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = IdentityAsyncClient( + 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_list_locations_flattened(): + client = IdentityClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = IdentityAsyncClient( + 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() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_get_location_flattened(): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = IdentityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_set_iam_policy_flattened(): + client = IdentityClient( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = IdentityAsyncClient( + 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() + ) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +def test_get_iam_policy(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_get_iam_policy_flattened(): + client = IdentityClient( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = IdentityAsyncClient( + 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() + ) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +def test_test_iam_permissions(transport: str = "grpc"): + client = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = IdentityAsyncClient( + 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 = IdentityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityAsyncClient( + 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_test_iam_permissions_flattened(): + client = IdentityClient( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = IdentityAsyncClient( + 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() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = IdentityClient( + 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 = IdentityAsyncClient( + 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 = IdentityClient( + 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 = IdentityClient( + 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", [ + (IdentityClient, transports.IdentityGrpcTransport), + (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport), +]) +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/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py new file mode 100644 index 000000000000..c39840595a01 --- /dev/null +++ b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py @@ -0,0 +1,11873 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 asyncio +import re +from unittest import mock +from unittest.mock import AsyncMock + +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 collections.abc import Sequence, Mapping +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 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.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.showcase_v1beta1.services.messaging import MessagingAsyncClient +from google.showcase_v1beta1.services.messaging import MessagingClient +from google.showcase_v1beta1.services.messaging import pagers +from google.showcase_v1beta1.services.messaging import transports +from google.showcase_v1beta1.types import messaging +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) +_UUID4_RE = re.compile(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}") + + +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 + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert MessagingClient._get_default_mtls_endpoint(None) is None + assert MessagingClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert MessagingClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert MessagingClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert MessagingClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert MessagingClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert MessagingClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + +def test__read_environment_variables(): + assert MessagingClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert MessagingClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert MessagingClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + MessagingClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert MessagingClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert MessagingClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert MessagingClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert MessagingClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + MessagingClient._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 MessagingClient._read_environment_variables() == (False, "auto", "foo.com") + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): + assert MessagingClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): + assert MessagingClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert MessagingClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert MessagingClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert MessagingClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): + assert MessagingClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert MessagingClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): + assert MessagingClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert MessagingClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + with pytest.raises(ValueError): + MessagingClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + assert MessagingClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert MessagingClient._use_client_cert_effective() is False + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert MessagingClient._get_client_cert_source(None, False) is None + assert MessagingClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert MessagingClient._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 MessagingClient._get_client_cert_source(None, True) is mock_default_cert_source + assert MessagingClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) +@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = MessagingClient._DEFAULT_UNIVERSE + default_endpoint = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert MessagingClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert MessagingClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == MessagingClient.DEFAULT_MTLS_ENDPOINT + assert MessagingClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert MessagingClient._get_api_endpoint(None, None, default_universe, "always") == MessagingClient.DEFAULT_MTLS_ENDPOINT + assert MessagingClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == MessagingClient.DEFAULT_MTLS_ENDPOINT + assert MessagingClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert MessagingClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + MessagingClient._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 MessagingClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert MessagingClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert MessagingClient._get_universe_domain(None, None) == MessagingClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + MessagingClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = MessagingClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = MessagingClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +def test__setup_request_id(): + class MockRequest: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + def __contains__(self, key): + return hasattr(self, key) + + class MockProtoRequest: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + def HasField(self, key): + return hasattr(self, key) + + # Test with proto3 optional field not in request + request = MockRequest() + MessagingClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with proto3 optional field already in request + request = MockRequest(request_id="already_set") + MessagingClient._setup_request_id(request, "request_id", True) + assert request.request_id == "already_set" + + # Test with non-proto3 optional field empty + request = MockRequest(request_id="") + MessagingClient._setup_request_id(request, "request_id", False) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with non-proto3 optional field already set + request = MockRequest(request_id="already_set") + MessagingClient._setup_request_id(request, "request_id", False) + assert request.request_id == "already_set" + + # Test with proto3 optional field not in request (MockProtoRequest) + request = MockProtoRequest() + MessagingClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with proto3 optional field already in request (MockProtoRequest) + request = MockProtoRequest(request_id="already_set") + MessagingClient._setup_request_id(request, "request_id", True) + assert request.request_id == "already_set" + + # Test with ValueError + class MockValueErrorRequest: + def HasField(self, key): + raise ValueError("Mismatched field") + def __contains__(self, key): + return hasattr(self, key) + + request = MockValueErrorRequest() + MessagingClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) + + # Test with dict and proto3 optional field not in request + request = {} + MessagingClient._setup_request_id(request, "request_id", True) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) + + # Test with dict and proto3 optional field already in request + request = {"request_id": "already_set"} + MessagingClient._setup_request_id(request, "request_id", True) + assert request["request_id"] == "already_set" + + # Test with dict and non-proto3 optional field empty + request = {"request_id": ""} + MessagingClient._setup_request_id(request, "request_id", False) + assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) + + # Test with dict and non-proto3 optional field already set + request = {"request_id": "already_set"} + MessagingClient._setup_request_id(request, "request_id", False) + assert request["request_id"] == "already_set" + +@pytest.mark.parametrize("client_class,transport_name", [ + (MessagingClient, "grpc"), + (MessagingAsyncClient, "grpc_asyncio"), + (MessagingClient, "rest"), +]) +def test_messaging_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 == ( + 'localhost:7469' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://localhost:7469' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.MessagingGrpcTransport, "grpc"), + (transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.MessagingRestTransport, "rest"), +]) +def test_messaging_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", [ + (MessagingClient, "grpc"), + (MessagingAsyncClient, "grpc_asyncio"), + (MessagingClient, "rest"), +]) +def test_messaging_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 == ( + 'localhost:7469' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://localhost:7469' + ) + + +def test_messaging_client_get_transport_class(): + transport = MessagingClient.get_transport_class() + available_transports = [ + transports.MessagingGrpcTransport, + transports.MessagingRestTransport, + ] + assert transport in available_transports + + transport = MessagingClient.get_transport_class("grpc") + assert transport == transports.MessagingGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (MessagingClient, transports.MessagingGrpcTransport, "grpc"), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio"), + (MessagingClient, transports.MessagingRestTransport, "rest"), +]) +@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) +@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) +def test_messaging_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(MessagingClient, '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(MessagingClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (MessagingClient, transports.MessagingGrpcTransport, "grpc", "true"), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (MessagingClient, transports.MessagingGrpcTransport, "grpc", "false"), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (MessagingClient, transports.MessagingRestTransport, "rest", "true"), + (MessagingClient, transports.MessagingRestTransport, "rest", "false"), +]) +@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) +@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_messaging_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", [ + MessagingClient, MessagingAsyncClient +]) +@mock.patch.object(MessagingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MessagingClient)) +@mock.patch.object(MessagingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MessagingAsyncClient)) +def test_messaging_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + +@pytest.mark.parametrize("client_class", [ + MessagingClient, MessagingAsyncClient +]) +@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) +@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) +def test_messaging_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = MessagingClient._DEFAULT_UNIVERSE + default_endpoint = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = MessagingClient._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", [ + (MessagingClient, transports.MessagingGrpcTransport, "grpc"), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio"), + (MessagingClient, transports.MessagingRestTransport, "rest"), +]) +def test_messaging_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", [ + (MessagingClient, transports.MessagingGrpcTransport, "grpc", grpc_helpers), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (MessagingClient, transports.MessagingRestTransport, "rest", None), +]) +def test_messaging_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_messaging_client_client_options_from_dict(): + with mock.patch('google.showcase_v1beta1.services.messaging.transports.MessagingGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = MessagingClient( + 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", [ + (MessagingClient, transports.MessagingGrpcTransport, "grpc", grpc_helpers), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_messaging_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( + "localhost:7469", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="localhost:7469", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.CreateRoomRequest(), + {}, +]) +def test_create_room(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.create_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.CreateRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_room_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 = MessagingClient( + 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 = messaging.CreateRoomRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_room(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateRoomRequest( + ) + assert args[0] == request_msg + +def test_create_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + request = {} + client.create_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_room(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_room_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 = MessagingAsyncClient( + 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_room 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_room] = mock_rpc + + request = {} + await client.create_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_room(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 +@pytest.mark.parametrize("request_type", [ + messaging.CreateRoomRequest(), + {}, +]) +async def test_create_room_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.CreateRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_room_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_room( + display_name='display_name_value', + description='description_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].room.display_name + mock_val = 'display_name_value' + assert arg == mock_val + arg = args[0].room.description + mock_val = 'description_value' + assert arg == mock_val + + +def test_create_room_flattened_error(): + client = MessagingClient( + credentials=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_room( + messaging.CreateRoomRequest(), + display_name='display_name_value', + description='description_value', + ) + +@pytest.mark.asyncio +async def test_create_room_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_room( + display_name='display_name_value', + description='description_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].room.display_name + mock_val = 'display_name_value' + assert arg == mock_val + arg = args[0].room.description + mock_val = 'description_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_room_flattened_error_async(): + client = MessagingAsyncClient( + 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_room( + messaging.CreateRoomRequest(), + display_name='display_name_value', + description='description_value', + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.GetRoomRequest(), + {}, +]) +def test_get_room(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.GetRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_room_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 = MessagingClient( + 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 = messaging.GetRoomRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_room(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetRoomRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_get_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + request = {} + client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_room(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_room_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 = MessagingAsyncClient( + 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_room 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_room] = mock_rpc + + request = {} + await client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_room(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 +@pytest.mark.parametrize("request_type", [ + messaging.GetRoomRequest(), + {}, +]) +async def test_get_room_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.GetRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_room_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.GetRoomRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + call.return_value = messaging.Room() + client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_room_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.GetRoomRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) + await client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_room_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_room( + name='name_value', + ) + + # Establish that the 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_room_flattened_error(): + client = MessagingClient( + credentials=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_room( + messaging.GetRoomRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_room_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_room( + name='name_value', + ) + + # Establish that 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_room_flattened_error_async(): + client = MessagingAsyncClient( + 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_room( + messaging.GetRoomRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.UpdateRoomRequest(), + {}, +]) +def test_update_room(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.UpdateRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_room_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 = MessagingClient( + 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 = messaging.UpdateRoomRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_room(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateRoomRequest( + ) + assert args[0] == request_msg + +def test_update_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + request = {} + client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_room(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_room_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 = MessagingAsyncClient( + 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_room 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_room] = mock_rpc + + request = {} + await client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_room(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 +@pytest.mark.parametrize("request_type", [ + messaging.UpdateRoomRequest(), + {}, +]) +async def test_update_room_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.UpdateRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_update_room_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.UpdateRoomRequest() + + request.room.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + call.return_value = messaging.Room() + client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'room.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_room_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.UpdateRoomRequest() + + request.room.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) + await client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'room.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + messaging.DeleteRoomRequest(), + {}, +]) +def test_delete_room(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.DeleteRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_room_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 = MessagingClient( + 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 = messaging.DeleteRoomRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_room(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteRoomRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_delete_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + request = {} + client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_room(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_room_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 = MessagingAsyncClient( + 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_room 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_room] = mock_rpc + + request = {} + await client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_room(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 +@pytest.mark.parametrize("request_type", [ + messaging.DeleteRoomRequest(), + {}, +]) +async def test_delete_room_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.DeleteRoomRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_room_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.DeleteRoomRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + call.return_value = None + client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_room_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.DeleteRoomRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_room_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_room( + name='name_value', + ) + + # Establish that the 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_room_flattened_error(): + client = MessagingClient( + credentials=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_room( + messaging.DeleteRoomRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_room_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_room( + name='name_value', + ) + + # Establish that 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_room_flattened_error_async(): + client = MessagingAsyncClient( + 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_room( + messaging.DeleteRoomRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.ListRoomsRequest(), + {}, +]) +def test_list_rooms(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rooms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.ListRoomsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_rooms(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.ListRoomsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRoomsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_rooms_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 = MessagingClient( + 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 = messaging.ListRoomsRequest( + 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_rooms), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_rooms(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListRoomsRequest( + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_list_rooms_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 = MessagingClient( + 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_rooms 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_rooms] = mock_rpc + request = {} + client.list_rooms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_rooms(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_rooms_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 = MessagingAsyncClient( + 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_rooms 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_rooms] = mock_rpc + + request = {} + await client.list_rooms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_rooms(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 +@pytest.mark.parametrize("request_type", [ + messaging.ListRoomsRequest(), + {}, +]) +async def test_list_rooms_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_rooms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListRoomsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_rooms(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.ListRoomsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRoomsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_rooms_pager(transport_name: str = "grpc"): + client = MessagingClient( + 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_rooms), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + messaging.Room(), + ], + next_page_token='abc', + ), + messaging.ListRoomsResponse( + rooms=[], + next_page_token='def', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + ], + next_page_token='ghi', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_rooms(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, messaging.Room) + for i in results) +def test_list_rooms_pages(transport_name: str = "grpc"): + client = MessagingClient( + 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_rooms), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + messaging.Room(), + ], + next_page_token='abc', + ), + messaging.ListRoomsResponse( + rooms=[], + next_page_token='def', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + ], + next_page_token='ghi', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + ], + ), + RuntimeError, + ) + pages = list(client.list_rooms(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_rooms_async_pager(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rooms), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + messaging.Room(), + ], + next_page_token='abc', + ), + messaging.ListRoomsResponse( + rooms=[], + next_page_token='def', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + ], + next_page_token='ghi', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_rooms(request={},) + assert async_pager.next_page_token == 'abc' + assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, messaging.Room) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_rooms_async_pages(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rooms), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + messaging.Room(), + ], + next_page_token='abc', + ), + messaging.ListRoomsResponse( + rooms=[], + next_page_token='def', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + ], + next_page_token='ghi', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_rooms(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", [ + messaging.CreateBlurbRequest(), + {}, +]) +def test_create_blurb(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb( + name='name_value', + user='user_value', + text='text_value', + legacy_room_id='legacy_room_id_value', + ) + response = client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.CreateBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + + +def test_create_blurb_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 = MessagingClient( + 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 = messaging.CreateBlurbRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_blurb(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateBlurbRequest( + parent='parent_value', + ) + assert args[0] == request_msg + +def test_create_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + request = {} + client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_blurb(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_blurb_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 = MessagingAsyncClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + await client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_blurb(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 +@pytest.mark.parametrize("request_type", [ + messaging.CreateBlurbRequest(), + {}, +]) +async def test_create_blurb_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( + name='name_value', + user='user_value', + )) + response = await client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.CreateBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + +def test_create_blurb_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.CreateBlurbRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + call.return_value = messaging.Blurb() + client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_blurb_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.CreateBlurbRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) + await client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_blurb_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_blurb( + parent='parent_value', + user='user_value', + text='text_value', + image=b'image_blob', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].blurb.user + mock_val = 'user_value' + assert arg == mock_val + assert args[0].blurb.image == b'image_blob' + + +def test_create_blurb_flattened_error(): + client = MessagingClient( + credentials=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_blurb( + messaging.CreateBlurbRequest(), + parent='parent_value', + user='user_value', + text='text_value', + image=b'image_blob', + ) + +@pytest.mark.asyncio +async def test_create_blurb_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_blurb( + parent='parent_value', + user='user_value', + text='text_value', + image=b'image_blob', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].blurb.user + mock_val = 'user_value' + assert arg == mock_val + assert args[0].blurb.image == b'image_blob' + +@pytest.mark.asyncio +async def test_create_blurb_flattened_error_async(): + client = MessagingAsyncClient( + 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_blurb( + messaging.CreateBlurbRequest(), + parent='parent_value', + user='user_value', + text='text_value', + image=b'image_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.GetBlurbRequest(), + {}, +]) +def test_get_blurb(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb( + name='name_value', + user='user_value', + text='text_value', + legacy_room_id='legacy_room_id_value', + ) + response = client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.GetBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + + +def test_get_blurb_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 = MessagingClient( + 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 = messaging.GetBlurbRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_blurb(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetBlurbRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_get_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + request = {} + client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_blurb(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_blurb_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 = MessagingAsyncClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + await client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_blurb(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 +@pytest.mark.parametrize("request_type", [ + messaging.GetBlurbRequest(), + {}, +]) +async def test_get_blurb_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( + name='name_value', + user='user_value', + )) + response = await client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.GetBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + +def test_get_blurb_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.GetBlurbRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + call.return_value = messaging.Blurb() + client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_blurb_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.GetBlurbRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) + await client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_blurb_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_blurb( + name='name_value', + ) + + # Establish that the 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_blurb_flattened_error(): + client = MessagingClient( + credentials=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_blurb( + messaging.GetBlurbRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_blurb_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_blurb( + name='name_value', + ) + + # Establish that 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_blurb_flattened_error_async(): + client = MessagingAsyncClient( + 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_blurb( + messaging.GetBlurbRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.UpdateBlurbRequest(), + {}, +]) +def test_update_blurb(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.Blurb( + name='name_value', + user='user_value', + text='text_value', + legacy_room_id='legacy_room_id_value', + ) + response = client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.UpdateBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + + +def test_update_blurb_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 = MessagingClient( + 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 = messaging.UpdateBlurbRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_blurb(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateBlurbRequest( + ) + assert args[0] == request_msg + +def test_update_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + request = {} + client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_blurb(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_blurb_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 = MessagingAsyncClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + await client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_blurb(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 +@pytest.mark.parametrize("request_type", [ + messaging.UpdateBlurbRequest(), + {}, +]) +async def test_update_blurb_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( + name='name_value', + user='user_value', + )) + response = await client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.UpdateBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + +def test_update_blurb_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.UpdateBlurbRequest() + + request.blurb.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + call.return_value = messaging.Blurb() + client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'blurb.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_blurb_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.UpdateBlurbRequest() + + request.blurb.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) + await client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'blurb.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + messaging.DeleteBlurbRequest(), + {}, +]) +def test_delete_blurb(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.DeleteBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_blurb_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 = MessagingClient( + 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 = messaging.DeleteBlurbRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_blurb(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteBlurbRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_delete_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + request = {} + client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_blurb(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_blurb_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 = MessagingAsyncClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + await client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_blurb(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 +@pytest.mark.parametrize("request_type", [ + messaging.DeleteBlurbRequest(), + {}, +]) +async def test_delete_blurb_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.DeleteBlurbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_blurb_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.DeleteBlurbRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + call.return_value = None + client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_blurb_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.DeleteBlurbRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_blurb_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_blurb( + name='name_value', + ) + + # Establish that the 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_blurb_flattened_error(): + client = MessagingClient( + credentials=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_blurb( + messaging.DeleteBlurbRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_blurb_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_blurb( + name='name_value', + ) + + # Establish that 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_blurb_flattened_error_async(): + client = MessagingAsyncClient( + 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_blurb( + messaging.DeleteBlurbRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + messaging.ListBlurbsRequest(), + {}, +]) +def test_list_blurbs(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.ListBlurbsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.ListBlurbsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBlurbsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_blurbs_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 = MessagingClient( + 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 = messaging.ListBlurbsRequest( + 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_blurbs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_blurbs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListBlurbsRequest( + parent='parent_value', + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_list_blurbs_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 = MessagingClient( + 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_blurbs 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_blurbs] = mock_rpc + request = {} + client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_blurbs(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_blurbs_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 = MessagingAsyncClient( + 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_blurbs 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_blurbs] = mock_rpc + + request = {} + await client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_blurbs(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 +@pytest.mark.parametrize("request_type", [ + messaging.ListBlurbsRequest(), + {}, +]) +async def test_list_blurbs_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.ListBlurbsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBlurbsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_blurbs_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.ListBlurbsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + call.return_value = messaging.ListBlurbsResponse() + client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_blurbs_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.ListBlurbsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse()) + await client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_blurbs_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.ListBlurbsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_blurbs( + 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_blurbs_flattened_error(): + client = MessagingClient( + credentials=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_blurbs( + messaging.ListBlurbsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_blurbs_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.ListBlurbsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_blurbs( + 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_blurbs_flattened_error_async(): + client = MessagingAsyncClient( + 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_blurbs( + messaging.ListBlurbsRequest(), + parent='parent_value', + ) + + +def test_list_blurbs_pager(transport_name: str = "grpc"): + client = MessagingClient( + 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_blurbs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + messaging.Blurb(), + ], + next_page_token='abc', + ), + messaging.ListBlurbsResponse( + blurbs=[], + next_page_token='def', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + ], + next_page_token='ghi', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_blurbs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, messaging.Blurb) + for i in results) +def test_list_blurbs_pages(transport_name: str = "grpc"): + client = MessagingClient( + 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_blurbs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + messaging.Blurb(), + ], + next_page_token='abc', + ), + messaging.ListBlurbsResponse( + blurbs=[], + next_page_token='def', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + ], + next_page_token='ghi', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + ], + ), + RuntimeError, + ) + pages = list(client.list_blurbs(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_blurbs_async_pager(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + messaging.Blurb(), + ], + next_page_token='abc', + ), + messaging.ListBlurbsResponse( + blurbs=[], + next_page_token='def', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + ], + next_page_token='ghi', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_blurbs(request={},) + assert async_pager.next_page_token == 'abc' + assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, messaging.Blurb) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_blurbs_async_pages(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + messaging.Blurb(), + ], + next_page_token='abc', + ), + messaging.ListBlurbsResponse( + blurbs=[], + next_page_token='def', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + ], + next_page_token='ghi', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_blurbs(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", [ + messaging.SearchBlurbsRequest(), + {}, +]) +def test_search_blurbs(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.search_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.SearchBlurbsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_search_blurbs_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 = MessagingClient( + 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 = messaging.SearchBlurbsRequest( + query='query_value', + 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.search_blurbs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_blurbs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.SearchBlurbsRequest( + query='query_value', + parent='parent_value', + page_token='page_token_value', + ) + assert args[0] == request_msg + +def test_search_blurbs_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 = MessagingClient( + 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.search_blurbs 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.search_blurbs] = mock_rpc + request = {} + client.search_blurbs(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.search_blurbs(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_search_blurbs_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 = MessagingAsyncClient( + 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.search_blurbs 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.search_blurbs] = mock_rpc + + request = {} + await client.search_blurbs(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.search_blurbs(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 +@pytest.mark.parametrize("request_type", [ + messaging.SearchBlurbsRequest(), + {}, +]) +async def test_search_blurbs_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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.search_blurbs), + '__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.search_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.SearchBlurbsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_search_blurbs_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.SearchBlurbsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.search_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_blurbs_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.SearchBlurbsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.search_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_search_blurbs_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__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.search_blurbs( + parent='parent_value', + query='query_value', + ) + + # Establish that the 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].query + mock_val = 'query_value' + assert arg == mock_val + + +def test_search_blurbs_flattened_error(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_blurbs( + messaging.SearchBlurbsRequest(), + parent='parent_value', + query='query_value', + ) + +@pytest.mark.asyncio +async def test_search_blurbs_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__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.search_blurbs( + parent='parent_value', + query='query_value', + ) + + # Establish that 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].query + mock_val = 'query_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_blurbs_flattened_error_async(): + client = MessagingAsyncClient( + 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.search_blurbs( + messaging.SearchBlurbsRequest(), + parent='parent_value', + query='query_value', + ) + + +def test_search_blurbs_raw_page_lro(): + response = messaging.SearchBlurbsResponse() + assert response.raw_page is response + +@pytest.mark.parametrize("request_type", [ + messaging.StreamBlurbsRequest(), + {}, +]) +def test_stream_blurbs(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([messaging.StreamBlurbsResponse()]) + response = client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = messaging.StreamBlurbsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, messaging.StreamBlurbsResponse) + + +def test_stream_blurbs_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 = MessagingClient( + 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 = messaging.StreamBlurbsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stream_blurbs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.StreamBlurbsRequest( + name='name_value', + ) + assert args[0] == request_msg + +def test_stream_blurbs_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 = MessagingClient( + 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.stream_blurbs 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.stream_blurbs] = mock_rpc + request = {} + client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stream_blurbs(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_stream_blurbs_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 = MessagingAsyncClient( + 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.stream_blurbs 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.stream_blurbs] = mock_rpc + + request = {} + await client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stream_blurbs(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 +@pytest.mark.parametrize("request_type", [ + messaging.StreamBlurbsRequest(), + {}, +]) +async def test_stream_blurbs_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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.stream_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) + response = await client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = messaging.StreamBlurbsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, messaging.StreamBlurbsResponse) + +def test_stream_blurbs_field_headers(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = messaging.StreamBlurbsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + call.return_value = iter([messaging.StreamBlurbsResponse()]) + client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_stream_blurbs_field_headers_async(): + client = MessagingAsyncClient( + 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 = messaging.StreamBlurbsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) + await client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + messaging.CreateBlurbRequest(), + {}, +]) +def test_send_blurbs(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = messaging.SendBlurbsResponse( + names=['names_value'], + ) + response = client.send_blurbs(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.SendBlurbsResponse) + assert response.names == ['names_value'] + +def test_send_blurbs_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 = MessagingClient( + 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.send_blurbs 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.send_blurbs] = mock_rpc + request = [{}] + client.send_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_blurbs(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_send_blurbs_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 = MessagingAsyncClient( + 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.send_blurbs 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.send_blurbs] = mock_rpc + + request = [{}] + await client.send_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.send_blurbs(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 +@pytest.mark.parametrize("request_type", [ + messaging.CreateBlurbRequest(), + {}, +]) +async def test_send_blurbs_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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 + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeStreamUnaryCall(messaging.SendBlurbsResponse( + names=['names_value'], + )) + response = await (await client.send_blurbs(iter(requests))) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.SendBlurbsResponse) + assert response.names == ['names_value'] + + +@pytest.mark.parametrize("request_type", [ + messaging.ConnectRequest(), + {}, +]) +def test_connect(request_type, transport: str = 'grpc'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.connect), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([messaging.StreamBlurbsResponse()]) + response = client.connect(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, messaging.StreamBlurbsResponse) + +def test_connect_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 = MessagingClient( + 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.connect 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.connect] = mock_rpc + request = [{}] + client.connect(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.connect(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_connect_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 = MessagingAsyncClient( + 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.connect 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.connect] = mock_rpc + + request = [{}] + await client.connect(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.connect(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 +@pytest.mark.parametrize("request_type", [ + messaging.ConnectRequest(), + {}, +]) +async def test_connect_async(request_type, transport: str = 'grpc_asyncio'): + client = MessagingAsyncClient( + 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 + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.connect), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) + response = await client.connect(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, messaging.StreamBlurbsResponse) + + +def test_create_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + + request = {} + client.create_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_room(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_room_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Room() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + display_name='display_name_value', + description='description_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 = messaging.Room.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_room(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/rooms" % client.transport._host, args[1]) + + +def test_create_room_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_room( + messaging.CreateRoomRequest(), + display_name='display_name_value', + description='description_value', + ) + + +def test_get_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + + request = {} + client.get_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_room(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_room_rest_required_fields(request_type=messaging.GetRoomRequest): + transport_class = transports.MessagingRestTransport + + 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_room._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_room._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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = messaging.Room() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = messaging.Room.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_room(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_room_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_room._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_room_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Room() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'rooms/sample1'} + + # 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 = messaging.Room.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_room(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=rooms/*}" % client.transport._host, args[1]) + + +def test_get_room_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_room( + messaging.GetRoomRequest(), + name='name_value', + ) + + +def test_update_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + + request = {} + client.update_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_room(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_room_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 = MessagingClient( + 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_room 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_room] = mock_rpc + + request = {} + client.delete_room(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_room(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_room_rest_required_fields(request_type=messaging.DeleteRoomRequest): + transport_class = transports.MessagingRestTransport + + 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_room._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_room._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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_room(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_room_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_room._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_room_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'rooms/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_room(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=rooms/*}" % client.transport._host, args[1]) + + +def test_delete_room_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_room( + messaging.DeleteRoomRequest(), + name='name_value', + ) + + +def test_list_rooms_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 = MessagingClient( + 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_rooms 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_rooms] = mock_rpc + + request = {} + client.list_rooms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_rooms(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_rooms_rest_pager(transport: str = 'rest'): + client = MessagingClient( + 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 = ( + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + messaging.Room(), + ], + next_page_token='abc', + ), + messaging.ListRoomsResponse( + rooms=[], + next_page_token='def', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + ], + next_page_token='ghi', + ), + messaging.ListRoomsResponse( + rooms=[ + messaging.Room(), + messaging.Room(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(messaging.ListRoomsResponse.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 = {} + + pager = client.list_rooms(request=sample_request) + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, messaging.Room) + for i in results) + + pages = list(client.list_rooms(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + client.create_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_blurb(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_blurb_rest_required_fields(request_type=messaging.CreateBlurbRequest): + transport_class = transports.MessagingRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_blurb._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_blurb._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = messaging.Blurb() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_blurb(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_blurb_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_blurb._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_create_blurb_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Blurb() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'rooms/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user='user_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 = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_blurb(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=rooms/*}/blurbs" % client.transport._host, args[1]) + + +def test_create_blurb_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_blurb( + messaging.CreateBlurbRequest(), + parent='parent_value', + user='user_value', + text='text_value', + image=b'image_blob', + ) + + +def test_get_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + client.get_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_blurb(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_blurb_rest_required_fields(request_type=messaging.GetBlurbRequest): + transport_class = transports.MessagingRestTransport + + 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_blurb._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_blurb._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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = messaging.Blurb() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_blurb(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_blurb_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_blurb._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_blurb_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Blurb() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'rooms/sample1/blurbs/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_blurb(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=rooms/*/blurbs/*}" % client.transport._host, args[1]) + + +def test_get_blurb_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_blurb( + messaging.GetBlurbRequest(), + name='name_value', + ) + + +def test_update_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + client.update_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_blurb(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_blurb_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 = MessagingClient( + 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_blurb 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_blurb] = mock_rpc + + request = {} + client.delete_blurb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_blurb(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_blurb_rest_required_fields(request_type=messaging.DeleteBlurbRequest): + transport_class = transports.MessagingRestTransport + + 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_blurb._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_blurb._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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_blurb(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_blurb_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_blurb._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_blurb_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'rooms/sample1/blurbs/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_blurb(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=rooms/*/blurbs/*}" % client.transport._host, args[1]) + + +def test_delete_blurb_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_blurb( + messaging.DeleteBlurbRequest(), + name='name_value', + ) + + +def test_list_blurbs_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 = MessagingClient( + 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_blurbs 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_blurbs] = mock_rpc + + request = {} + client.list_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_blurbs(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_blurbs_rest_required_fields(request_type=messaging.ListBlurbsRequest): + transport_class = transports.MessagingRestTransport + + 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_blurbs._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_blurbs._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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = messaging.ListBlurbsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = messaging.ListBlurbsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_blurbs(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_blurbs_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_blurbs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_blurbs_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.ListBlurbsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'rooms/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = messaging.ListBlurbsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_blurbs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=rooms/*}/blurbs" % client.transport._host, args[1]) + + +def test_list_blurbs_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.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_blurbs( + messaging.ListBlurbsRequest(), + parent='parent_value', + ) + + +def test_list_blurbs_rest_pager(transport: str = 'rest'): + client = MessagingClient( + 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 = ( + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + messaging.Blurb(), + ], + next_page_token='abc', + ), + messaging.ListBlurbsResponse( + blurbs=[], + next_page_token='def', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + ], + next_page_token='ghi', + ), + messaging.ListBlurbsResponse( + blurbs=[ + messaging.Blurb(), + messaging.Blurb(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(messaging.ListBlurbsResponse.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': 'rooms/sample1'} + + pager = client.list_blurbs(request=sample_request) + + assert pager.next_page_token == 'abc' + assert str(pager).startswith(f'{pager.__class__.__name__}<') + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, messaging.Blurb) + for i in results) + + pages = list(client.list_blurbs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_search_blurbs_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 = MessagingClient( + 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.search_blurbs 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.search_blurbs] = mock_rpc + + request = {} + client.search_blurbs(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.search_blurbs(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_search_blurbs_rest_required_fields(request_type=messaging.SearchBlurbsRequest): + transport_class = transports.MessagingRestTransport + + request_init = {} + request_init["query"] = "" + 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()).search_blurbs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_blurbs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.search_blurbs(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_search_blurbs_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_blurbs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("query", ))) + + +def test_search_blurbs_rest_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'rooms/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + query='query_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.search_blurbs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=rooms/*}/blurbs:search" % client.transport._host, args[1]) + + +def test_search_blurbs_rest_flattened_error(transport: str = 'rest'): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_blurbs( + messaging.SearchBlurbsRequest(), + parent='parent_value', + query='query_value', + ) + + +def test_stream_blurbs_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 = MessagingClient( + 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.stream_blurbs 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.stream_blurbs] = mock_rpc + + request = {} + client.stream_blurbs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stream_blurbs(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_stream_blurbs_rest_required_fields(request_type=messaging.StreamBlurbsRequest): + transport_class = transports.MessagingRestTransport + + 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()).stream_blurbs._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()).stream_blurbs._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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = messaging.StreamBlurbsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.StreamBlurbsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.stream_blurbs(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert sorted(expected_params) == sorted(actual_params) + + +def test_stream_blurbs_rest_unset_required_fields(): + transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stream_blurbs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "expireTime", ))) + + +def test_send_blurbs_rest_unimplemented(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = messaging.CreateBlurbRequest() + requests = [request] + with pytest.raises(NotImplementedError): + client.send_blurbs(requests) + + +def test_connect_rest_no_http_options(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = messaging.ConnectRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.connect(requests) + + +def test_connect_rest_error(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.connect({}) + assert ( + "Method Connect is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.MessagingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.MessagingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MessagingClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.MessagingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = MessagingClient( + 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 = MessagingClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.MessagingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MessagingClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.MessagingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = MessagingClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.MessagingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.MessagingGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.MessagingGrpcTransport, + transports.MessagingGrpcAsyncIOTransport, + transports.MessagingRestTransport, +]) +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 = MessagingClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_room_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + call.return_value = messaging.Room() + client.create_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateRoomRequest() + assert args[0] == request_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_room_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + call.return_value = messaging.Room() + client.get_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetRoomRequest() + assert args[0] == request_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_room_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + call.return_value = messaging.Room() + client.update_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateRoomRequest() + assert args[0] == request_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_room_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + call.return_value = None + client.delete_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteRoomRequest() + assert args[0] == request_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_rooms_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_rooms), + '__call__') as call: + call.return_value = messaging.ListRoomsResponse() + client.list_rooms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListRoomsRequest() + assert args[0] == request_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_blurb_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + call.return_value = messaging.Blurb() + client.create_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateBlurbRequest() + assert args[0] == request_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_blurb_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + call.return_value = messaging.Blurb() + client.get_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetBlurbRequest() + assert args[0] == request_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_blurb_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + call.return_value = messaging.Blurb() + client.update_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateBlurbRequest() + assert args[0] == request_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_blurb_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + call.return_value = None + client.delete_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteBlurbRequest() + assert args[0] == request_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_blurbs_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + call.return_value = messaging.ListBlurbsResponse() + client.list_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListBlurbsRequest() + assert args[0] == request_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_search_blurbs_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.search_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.SearchBlurbsRequest() + assert args[0] == request_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_stream_blurbs_empty_call_grpc(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + call.return_value = iter([messaging.StreamBlurbsResponse()]) + client.stream_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.StreamBlurbsRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = MessagingAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_room_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + await client.create_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateRoomRequest() + assert args[0] == request_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_room_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + await client.get_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetRoomRequest() + assert args[0] == request_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_room_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + await client.update_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateRoomRequest() + assert args[0] == request_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_room_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteRoomRequest() + assert args[0] == request_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_rooms_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_rooms), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListRoomsResponse( + next_page_token='next_page_token_value', + )) + await client.list_rooms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListRoomsRequest() + assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( + name='name_value', + user='user_value', + )) + await client.create_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateBlurbRequest() + assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( + name='name_value', + user='user_value', + )) + await client.get_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetBlurbRequest() + assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( + name='name_value', + user='user_value', + )) + await client.update_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateBlurbRequest() + assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteBlurbRequest() + assert args[0] == request_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_blurbs_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse( + next_page_token='next_page_token_value', + )) + await client.list_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListBlurbsRequest() + assert args[0] == request_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_search_blurbs_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__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.search_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.SearchBlurbsRequest() + assert args[0] == request_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_stream_blurbs_empty_call_grpc_asyncio(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) + await client.stream_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.StreamBlurbsRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = MessagingClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_room_rest_bad_request(request_type=messaging.CreateRoomRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_room(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.CreateRoomRequest, + dict, +]) +def test_create_room_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.Room.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_room(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_room_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_create_room") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_create_room_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_create_room") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.CreateRoomRequest.pb(messaging.CreateRoomRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.Room.to_json(messaging.Room()) + req.return_value.content = return_value + + request = messaging.CreateRoomRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.Room() + post_with_metadata.return_value = messaging.Room(), metadata + + client.create_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_room_rest_bad_request(request_type=messaging.GetRoomRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_room(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.GetRoomRequest, + dict, +]) +def test_get_room_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.Room.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_room(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_room_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_get_room") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_get_room_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_get_room") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.GetRoomRequest.pb(messaging.GetRoomRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.Room.to_json(messaging.Room()) + req.return_value.content = return_value + + request = messaging.GetRoomRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.Room() + post_with_metadata.return_value = messaging.Room(), metadata + + client.get_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_room_rest_bad_request(request_type=messaging.UpdateRoomRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'room': {'name': 'rooms/sample1'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_room(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.UpdateRoomRequest, + dict, +]) +def test_update_room_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'room': {'name': 'rooms/sample1'}} + request_init["room"] = {'name': 'rooms/sample1', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = messaging.UpdateRoomRequest.meta.fields["room"] + + 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["room"].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["room"][field])): + del request_init["room"][field][i][subfield] + else: + del request_init["room"][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 = messaging.Room( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.Room.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_room(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Room) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_room_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_update_room") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_update_room_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_update_room") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.UpdateRoomRequest.pb(messaging.UpdateRoomRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.Room.to_json(messaging.Room()) + req.return_value.content = return_value + + request = messaging.UpdateRoomRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.Room() + post_with_metadata.return_value = messaging.Room(), metadata + + client.update_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_room_rest_bad_request(request_type=messaging.DeleteRoomRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_room(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.DeleteRoomRequest, + dict, +]) +def test_delete_room_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_room(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_room_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "pre_delete_room") as pre: + pre.assert_not_called() + pb_message = messaging.DeleteRoomRequest.pb(messaging.DeleteRoomRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = messaging.DeleteRoomRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_rooms_rest_bad_request(request_type=messaging.ListRoomsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_rooms(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.ListRoomsRequest, + dict, +]) +def test_list_rooms_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.ListRoomsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.ListRoomsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_rooms(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRoomsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rooms_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_list_rooms") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_list_rooms_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_list_rooms") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.ListRoomsRequest.pb(messaging.ListRoomsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.ListRoomsResponse.to_json(messaging.ListRoomsResponse()) + req.return_value.content = return_value + + request = messaging.ListRoomsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.ListRoomsResponse() + post_with_metadata.return_value = messaging.ListRoomsResponse(), metadata + + client.list_rooms(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_blurb_rest_bad_request(request_type=messaging.CreateBlurbRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_blurb(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.CreateBlurbRequest, + dict, +]) +def test_create_blurb_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.Blurb( + name='name_value', + user='user_value', + text='text_value', + legacy_room_id='legacy_room_id_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 = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_blurb(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_blurb_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_create_blurb") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_create_blurb_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_create_blurb") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.CreateBlurbRequest.pb(messaging.CreateBlurbRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.Blurb.to_json(messaging.Blurb()) + req.return_value.content = return_value + + request = messaging.CreateBlurbRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.Blurb() + post_with_metadata.return_value = messaging.Blurb(), metadata + + client.create_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_blurb_rest_bad_request(request_type=messaging.GetBlurbRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1/blurbs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_blurb(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.GetBlurbRequest, + dict, +]) +def test_get_blurb_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1/blurbs/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 = messaging.Blurb( + name='name_value', + user='user_value', + text='text_value', + legacy_room_id='legacy_room_id_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 = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_blurb(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_blurb_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_get_blurb") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_get_blurb_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_get_blurb") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.GetBlurbRequest.pb(messaging.GetBlurbRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.Blurb.to_json(messaging.Blurb()) + req.return_value.content = return_value + + request = messaging.GetBlurbRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.Blurb() + post_with_metadata.return_value = messaging.Blurb(), metadata + + client.get_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_blurb_rest_bad_request(request_type=messaging.UpdateBlurbRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'blurb': {'name': 'rooms/sample1/blurbs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_blurb(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.UpdateBlurbRequest, + dict, +]) +def test_update_blurb_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'blurb': {'name': 'rooms/sample1/blurbs/sample2'}} + request_init["blurb"] = {'name': 'rooms/sample1/blurbs/sample2', 'user': 'user_value', 'text': 'text_value', 'image': b'image_blob', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'legacy_room_id': 'legacy_room_id_value', 'legacy_user_id': 'legacy_user_id_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 = messaging.UpdateBlurbRequest.meta.fields["blurb"] + + 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["blurb"].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["blurb"][field])): + del request_init["blurb"][field][i][subfield] + else: + del request_init["blurb"][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 = messaging.Blurb( + name='name_value', + user='user_value', + text='text_value', + legacy_room_id='legacy_room_id_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 = messaging.Blurb.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_blurb(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.Blurb) + assert response.name == 'name_value' + assert response.user == 'user_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_blurb_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_update_blurb") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_update_blurb_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_update_blurb") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.UpdateBlurbRequest.pb(messaging.UpdateBlurbRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.Blurb.to_json(messaging.Blurb()) + req.return_value.content = return_value + + request = messaging.UpdateBlurbRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.Blurb() + post_with_metadata.return_value = messaging.Blurb(), metadata + + client.update_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_blurb_rest_bad_request(request_type=messaging.DeleteBlurbRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1/blurbs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_blurb(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.DeleteBlurbRequest, + dict, +]) +def test_delete_blurb_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1/blurbs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_blurb(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_blurb_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "pre_delete_blurb") as pre: + pre.assert_not_called() + pb_message = messaging.DeleteBlurbRequest.pb(messaging.DeleteBlurbRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = messaging.DeleteBlurbRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_blurbs_rest_bad_request(request_type=messaging.ListBlurbsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_blurbs(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.ListBlurbsRequest, + dict, +]) +def test_list_blurbs_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.ListBlurbsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = messaging.ListBlurbsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_blurbs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBlurbsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_blurbs_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_list_blurbs") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_list_blurbs_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_list_blurbs") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.ListBlurbsRequest.pb(messaging.ListBlurbsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.ListBlurbsResponse.to_json(messaging.ListBlurbsResponse()) + req.return_value.content = return_value + + request = messaging.ListBlurbsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.ListBlurbsResponse() + post_with_metadata.return_value = messaging.ListBlurbsResponse(), metadata + + client.list_blurbs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_search_blurbs_rest_bad_request(request_type=messaging.SearchBlurbsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.search_blurbs(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.SearchBlurbsRequest, + dict, +]) +def test_search_blurbs_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.search_blurbs(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_search_blurbs_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_search_blurbs") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_search_blurbs_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_search_blurbs") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.SearchBlurbsRequest.pb(messaging.SearchBlurbsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = messaging.SearchBlurbsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.search_blurbs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_stream_blurbs_rest_bad_request(request_type=messaging.StreamBlurbsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.stream_blurbs(request) + + +@pytest.mark.parametrize("request_type", [ + messaging.StreamBlurbsRequest, + dict, +]) +def test_stream_blurbs_rest_call_success(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'rooms/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = messaging.StreamBlurbsResponse( + action=messaging.StreamBlurbsResponse.Action.CREATE, + ) + + # 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 = messaging.StreamBlurbsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.stream_blurbs(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, messaging.StreamBlurbsResponse) + assert response.action == messaging.StreamBlurbsResponse.Action.CREATE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stream_blurbs_rest_interceptors(null_interceptor): + transport = transports.MessagingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), + ) + client = MessagingClient(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.MessagingRestInterceptor, "post_stream_blurbs") as post, \ + mock.patch.object(transports.MessagingRestInterceptor, "post_stream_blurbs_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.MessagingRestInterceptor, "pre_stream_blurbs") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = messaging.StreamBlurbsRequest.pb(messaging.StreamBlurbsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = messaging.StreamBlurbsResponse.to_json(messaging.StreamBlurbsResponse()) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = messaging.StreamBlurbsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = messaging.StreamBlurbsResponse() + post_with_metadata.return_value = messaging.StreamBlurbsResponse(), metadata + + client.stream_blurbs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_send_blurbs_rest_error(): + + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.send_blurbs({}) + assert ( + "Method SendBlurbs is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_connect_rest_error(): + + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.connect({}) + assert ( + "Method Connect is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'users/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'users/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 = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'operations/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'operations/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_initialize_client_w_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_room_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_room), + '__call__') as call: + client.create_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateRoomRequest() + assert args[0] == request_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_room_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_room), + '__call__') as call: + client.get_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetRoomRequest() + assert args[0] == request_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_room_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_room), + '__call__') as call: + client.update_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateRoomRequest() + assert args[0] == request_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_room_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_room), + '__call__') as call: + client.delete_room(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteRoomRequest() + assert args[0] == request_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_rooms_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_rooms), + '__call__') as call: + client.list_rooms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListRoomsRequest() + assert args[0] == request_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_blurb_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_blurb), + '__call__') as call: + client.create_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.CreateBlurbRequest() + assert args[0] == request_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_blurb_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_blurb), + '__call__') as call: + client.get_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.GetBlurbRequest() + assert args[0] == request_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_blurb_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_blurb), + '__call__') as call: + client.update_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.UpdateBlurbRequest() + assert args[0] == request_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_blurb_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_blurb), + '__call__') as call: + client.delete_blurb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.DeleteBlurbRequest() + assert args[0] == request_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_blurbs_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_blurbs), + '__call__') as call: + client.list_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.ListBlurbsRequest() + assert args[0] == request_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_search_blurbs_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_blurbs), + '__call__') as call: + client.search_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.SearchBlurbsRequest() + assert args[0] == request_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_stream_blurbs_empty_call_rest(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stream_blurbs), + '__call__') as call: + client.stream_blurbs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = messaging.StreamBlurbsRequest() + assert args[0] == request_msg + + +def test_messaging_rest_lro_client(): + client = MessagingClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.MessagingGrpcTransport, + ) + +def test_messaging_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.MessagingTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_messaging_base_transport(): + # Instantiate the base transport. + with mock.patch('google.showcase_v1beta1.services.messaging.transports.MessagingTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.MessagingTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_room', + 'get_room', + 'update_room', + 'delete_room', + 'list_rooms', + 'create_blurb', + 'get_blurb', + 'update_blurb', + 'delete_blurb', + 'list_blurbs', + 'search_blurbs', + 'stream_blurbs', + 'send_blurbs', + 'connect', + '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_messaging_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.showcase_v1beta1.services.messaging.transports.MessagingTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MessagingTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_messaging_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.showcase_v1beta1.services.messaging.transports.MessagingTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MessagingTransport() + adc.assert_called_once() + + +def test_messaging_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) + MessagingClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MessagingGrpcTransport, + transports.MessagingGrpcAsyncIOTransport, + ], +) +def test_messaging_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MessagingGrpcTransport, + transports.MessagingGrpcAsyncIOTransport, + transports.MessagingRestTransport, + ], +) +def test_messaging_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.MessagingGrpcTransport, grpc_helpers), + (transports.MessagingGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_messaging_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( + "localhost:7469", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="localhost:7469", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.MessagingGrpcTransport, transports.MessagingGrpcAsyncIOTransport]) +def test_messaging_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_messaging_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.MessagingRestTransport ( + 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_messaging_host_no_port(transport_name): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='localhost'), + transport=transport_name, + ) + assert client.transport._host == ( + 'localhost:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://localhost' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_messaging_host_with_port(transport_name): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='localhost:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'localhost:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://localhost:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_messaging_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = MessagingClient( + credentials=creds1, + transport=transport_name, + ) + client2 = MessagingClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_room._session + session2 = client2.transport.create_room._session + assert session1 != session2 + session1 = client1.transport.get_room._session + session2 = client2.transport.get_room._session + assert session1 != session2 + session1 = client1.transport.update_room._session + session2 = client2.transport.update_room._session + assert session1 != session2 + session1 = client1.transport.delete_room._session + session2 = client2.transport.delete_room._session + assert session1 != session2 + session1 = client1.transport.list_rooms._session + session2 = client2.transport.list_rooms._session + assert session1 != session2 + session1 = client1.transport.create_blurb._session + session2 = client2.transport.create_blurb._session + assert session1 != session2 + session1 = client1.transport.get_blurb._session + session2 = client2.transport.get_blurb._session + assert session1 != session2 + session1 = client1.transport.update_blurb._session + session2 = client2.transport.update_blurb._session + assert session1 != session2 + session1 = client1.transport.delete_blurb._session + session2 = client2.transport.delete_blurb._session + assert session1 != session2 + session1 = client1.transport.list_blurbs._session + session2 = client2.transport.list_blurbs._session + assert session1 != session2 + session1 = client1.transport.search_blurbs._session + session2 = client2.transport.search_blurbs._session + assert session1 != session2 + session1 = client1.transport.stream_blurbs._session + session2 = client2.transport.stream_blurbs._session + assert session1 != session2 + session1 = client1.transport.send_blurbs._session + session2 = client2.transport.send_blurbs._session + assert session1 != session2 + session1 = client1.transport.connect._session + session2 = client2.transport.connect._session + assert session1 != session2 +def test_messaging_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.MessagingGrpcTransport( + 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_messaging_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.MessagingGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("transport_class", [transports.MessagingGrpcTransport, transports.MessagingGrpcAsyncIOTransport]) +def test_messaging_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.MessagingGrpcTransport, transports.MessagingGrpcAsyncIOTransport]) +def test_messaging_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_messaging_grpc_lro_client(): + client = MessagingClient( + 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_messaging_grpc_lro_async_client(): + client = MessagingAsyncClient( + 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_blurb_path(): + user = "squid" + legacy_user = "clam" + blurb = "whelk" + expected = "users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}".format(user=user, legacy_user=legacy_user, blurb=blurb, ) + actual = MessagingClient.blurb_path(user, legacy_user, blurb) + assert expected == actual + + +def test_parse_blurb_path(): + expected = { + "user": "octopus", + "legacy_user": "oyster", + "blurb": "nudibranch", + } + path = MessagingClient.blurb_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_blurb_path(path) + assert expected == actual + +def test_room_path(): + room = "cuttlefish" + expected = "rooms/{room}".format(room=room, ) + actual = MessagingClient.room_path(room) + assert expected == actual + + +def test_parse_room_path(): + expected = { + "room": "mussel", + } + path = MessagingClient.room_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_room_path(path) + assert expected == actual + +def test_user_path(): + user = "winkle" + expected = "users/{user}".format(user=user, ) + actual = MessagingClient.user_path(user) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "user": "nautilus", + } + path = MessagingClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = MessagingClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = MessagingClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = MessagingClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = MessagingClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = MessagingClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = MessagingClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = MessagingClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = MessagingClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = MessagingClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = MessagingClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = MessagingClient.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.MessagingTransport, '_prep_wrapped_messages') as prep: + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.MessagingTransport, '_prep_wrapped_messages') as prep: + transport_class = MessagingClient.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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_delete_operation_flattened(): + client = MessagingClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = MessagingAsyncClient( + 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 + ) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_cancel_operation_flattened(): + client = MessagingClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = MessagingAsyncClient( + 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 + ) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_get_operation_flattened(): + client = MessagingClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = MessagingAsyncClient( + 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() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_operations_flattened(): + client = MessagingClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = MessagingAsyncClient( + 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_list_locations_flattened(): + client = MessagingClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = MessagingAsyncClient( + 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() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_get_location_flattened(): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = MessagingAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_set_iam_policy_flattened(): + client = MessagingClient( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = MessagingAsyncClient( + 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() + ) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +def test_get_iam_policy(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_get_iam_policy_flattened(): + client = MessagingClient( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = MessagingAsyncClient( + 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() + ) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +def test_test_iam_permissions(transport: str = "grpc"): + client = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = MessagingAsyncClient( + 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 = MessagingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingAsyncClient( + 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_test_iam_permissions_flattened(): + client = MessagingClient( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = MessagingAsyncClient( + 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() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = MessagingClient( + 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 = MessagingAsyncClient( + 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 = MessagingClient( + 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 = MessagingClient( + 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", [ + (MessagingClient, transports.MessagingGrpcTransport), + (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport), +]) +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/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index 52209f41ff38..d56fed3e20f7 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -350,6 +350,7 @@ def showcase_library( ) # Install the generated showcase library. + session.install("-e", "../google-api-core") if templates == "DEFAULT": # Use the constraints file for the specific python runtime version. # We do this to make sure that we're testing against the lowest @@ -380,6 +381,9 @@ def showcase_library( # Install the library without a constraints file. session.install("-e", tmp_dir) + import shutil + shutil.rmtree("generated_showcase", ignore_errors=True) + shutil.copytree(tmp_dir, "generated_showcase") yield tmp_dir @@ -504,6 +508,10 @@ def run_showcase_unit_tests(session, fail_under=100, rest_async_io_enabled=False session.run("python", "-m", "pip", "freeze") # Run the tests. + import os + env = os.environ.copy() + env["GOOGLE_API_USE_CLIENT_CERTIFICATE"] = "false" + env["CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE"] = "" session.run( "py.test", *( @@ -517,6 +525,7 @@ def run_showcase_unit_tests(session, fail_under=100, rest_async_io_enabled=False path.join("tests", "unit"), ] ), + env=env, ) From dfca3e08586c41e95e73f390e537a634965d977b Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 21 Jul 2026 23:12:34 +0000 Subject: [PATCH 2/5] fix(generator): use unified _compat.py.j2 and remove downstream tests --- .../%name_%version/%sub/_compat.py.j2 | 182 +++++++++++++++++- .../tests/unit/generator/test_generator.py | 11 +- 2 files changed, 185 insertions(+), 8 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index 753dd6026676..368b13450a76 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -1,6 +1,183 @@ # {% include '_license.j2' %} -from typing import Any, Dict, List, Optional, Tuple +"""A compatibility module for older versions of google-api-core.""" + +import functools +import json +import operator +import os +import re +import uuid +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +from google.auth.exceptions import MutualTLSChannelError +import google.protobuf.message + + +try: + from google.api_core.universe import ( + get_default_mtls_endpoint, + get_api_endpoint, + get_universe_domain, + ) +except ImportError: + # TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Remove these fallbacks when google-api-core >= 2.18.0 is the minimum required version. + def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: + """Converts api endpoint to mTLS 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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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") + + def get_api_endpoint( + api_override: Optional[str], + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]], + universe_domain: str, + use_mtls_endpoint: str, + default_universe: str, + default_mtls_endpoint: Optional[str], + default_endpoint_template: str, + ) -> Optional[str]: + """Return the API endpoint 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): + if universe_domain != default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {default_universe}." + ) + api_endpoint = default_mtls_endpoint + else: + api_endpoint = default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + def get_universe_domain( + client_universe_domain: Optional[str], + universe_domain_env: Optional[str], + default_universe: str, + ) -> str: + """Return the universe domain used by the client.""" + universe_domain = 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 + + +try: + from google.api_core.gapic_v1.config import ( + use_client_cert_effective, + get_client_cert_source, + read_environment_variables, + ) +except ImportError: + from google.auth.transport import mtls # type: ignore + + # TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Remove these fallbacks when google-api-core >= 2.18.0 is the minimum required version. + + def use_client_cert_effective() -> bool: + """Returns whether client certificate should be used for mTLS.""" + if hasattr(mtls, "should_use_client_cert"): + return mtls.should_use_client_cert() + else: + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + def get_client_cert_source( + provided_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]], + use_cert_flag: bool, + ) -> Optional[Callable[[], Tuple[bytes, bytes]]]: + """Return 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 ( + hasattr(mtls, "has_default_client_cert_source") + and mtls.has_default_client_cert_source() + ): + client_cert_source = mtls.default_client_cert_source() + else: + raise ValueError( + "Client certificate is required for mTLS, but no client certificate source was provided or found." + ) + return client_cert_source + + def read_environment_variables() -> Tuple[bool, str, Optional[str]]: + """Returns the environment variables used by the client.""" + use_client_cert = use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` " + "must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + +try: + from google.api_core.gapic_v1.request import setup_request_id # type: ignore +except ImportError: + # TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Remove this fallback when google-api-core >= 2.26.0 is the minimum required version. + def setup_request_id(request, field_name: str, is_proto3_optional: bool): + """Populate a UUID4 field in the request if it is not already set. + + Args: + request (Union[google.protobuf.message.Message, dict]): The request object. + field_name (str): The name of the field to populate. + is_proto3_optional (bool): Whether the field is proto3 optional. + """ + request_id_val = str(uuid.uuid4()) + if request is None: + return + + if isinstance(request, dict): + if is_proto3_optional: + if field_name not in request or request[field_name] is None: + request[field_name] = request_id_val + elif not request.get(field_name): + request[field_name] = request_id_val + return + + if is_proto3_optional: + try: + # Pure protobuf messages + if not request.HasField(field_name): + setattr(request, field_name, request_id_val) + except (AttributeError, ValueError): + # Proto-plus messages or other objects + if getattr(request, field_name, None) is None: + setattr(request, field_name, request_id_val) + else: + if not getattr(request, field_name, None): + setattr(request, field_name, request_id_val) + try: from google.api_core.rest_helpers import ( @@ -9,9 +186,6 @@ try: ) except ImportError: # pragma: NO COVER # TODO: Remove these fallbacks when google-api-core >= 2.18.0 is the minimum required version. - import functools - import json - import operator from google.protobuf import json_format # type: ignore from google.api_core import path_template # type: ignore diff --git a/packages/gapic-generator/tests/unit/generator/test_generator.py b/packages/gapic-generator/tests/unit/generator/test_generator.py index 9d8545c4192f..f1566ee6e5a7 100644 --- a/packages/gapic-generator/tests/unit/generator/test_generator.py +++ b/packages/gapic-generator/tests/unit/generator/test_generator.py @@ -117,6 +117,8 @@ def test_get_response_ignores_private_files(): list_templates.return_value = [ "foo/bar/baz.py.j2", "foo/bar/_base.py.j2", + "foo/bar/__init__.py.j2", + "foo/bar/_compat.py.j2", "molluscs/squid/sample.py.j2", ] with mock.patch.object(jinja2.Environment, "get_template") as get_template: @@ -128,12 +130,13 @@ def test_get_response_ignores_private_files(): get_template.assert_has_calls( [ mock.call("molluscs/squid/sample.py.j2"), + mock.call("foo/bar/__init__.py.j2"), + mock.call("foo/bar/_compat.py.j2"), mock.call("foo/bar/baz.py.j2"), - ] + ], + any_order=True, ) - assert len(cgr.file) == 1 - assert cgr.file[0].name == "foo/bar/baz.py" - assert cgr.file[0].content == "I am a template result.\n" + assert len(cgr.file) == 3 def test_get_response_fails_invalid_file_paths(): From a3077d3e1dc3cfc77ee63c0787f6d38543c1cb96 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 21 Jul 2026 23:44:34 +0000 Subject: [PATCH 3/5] ci: re-trigger checks for PR 17766 From 259fbd3052aea63c0f7c9c76f0a019825f62a5d1 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 21 Jul 2026 23:46:24 +0000 Subject: [PATCH 4/5] chore(generator): remove generated_showcase from repository --- .../generated_showcase/.coveragerc | 13 - .../generated_showcase/.flake8 | 34 - .../generated_showcase/LICENSE | 202 - .../generated_showcase/MANIFEST.in | 20 - .../generated_showcase/README.rst | 143 - .../docs/_static/custom.css | 20 - .../docs/_templates/layout.html | 50 - .../generated_showcase/docs/conf.py | 417 - .../generated_showcase/docs/index.rst | 10 - .../docs/multiprocessing.rst | 7 - .../docs/showcase_v1beta1/echo.rst | 10 - .../docs/showcase_v1beta1/identity.rst | 10 - .../docs/showcase_v1beta1/messaging.rst | 10 - .../docs/showcase_v1beta1/services_.rst | 8 - .../docs/showcase_v1beta1/types_.rst | 6 - .../google/showcase/__init__.py | 127 - .../google/showcase/gapic_version.py | 16 - .../google/showcase/py.typed | 2 - .../google/showcase_v1beta1/__init__.py | 223 - .../google/showcase_v1beta1/_compat.py | 108 - .../google/showcase_v1beta1/gapic_version.py | 16 - .../google/showcase_v1beta1/py.typed | 2 - .../showcase_v1beta1/services/__init__.py | 15 - .../services/echo/__init__.py | 22 - .../services/echo/async_client.py | 1937 --- .../showcase_v1beta1/services/echo/client.py | 2361 --- .../showcase_v1beta1/services/echo/pagers.py | 450 - .../services/echo/transports/README.rst | 10 - .../services/echo/transports/__init__.py | 38 - .../services/echo/transports/base.py | 455 - .../services/echo/transports/grpc.py | 831 -- .../services/echo/transports/grpc_asyncio.py | 972 -- .../services/echo/transports/rest.py | 2975 ---- .../services/echo/transports/rest_base.py | 412 - .../services/identity/__init__.py | 22 - .../services/identity/async_client.py | 1441 -- .../services/identity/client.py | 1872 --- .../services/identity/pagers.py | 166 - .../services/identity/transports/README.rst | 10 - .../services/identity/transports/__init__.py | 38 - .../services/identity/transports/base.py | 370 - .../services/identity/transports/grpc.py | 649 - .../identity/transports/grpc_asyncio.py | 755 - .../services/identity/transports/rest.py | 2270 --- .../services/identity/transports/rest_base.py | 354 - .../services/messaging/__init__.py | 22 - .../services/messaging/async_client.py | 2367 --- .../services/messaging/client.py | 2811 ---- .../services/messaging/pagers.py | 305 - .../services/messaging/transports/README.rst | 10 - .../services/messaging/transports/__init__.py | 38 - .../services/messaging/transports/base.py | 542 - .../services/messaging/transports/grpc.py | 917 -- .../messaging/transports/grpc_asyncio.py | 1108 -- .../services/messaging/transports/rest.py | 3559 ----- .../messaging/transports/rest_base.py | 524 - .../google/showcase_v1beta1/types/__init__.py | 116 - .../google/showcase_v1beta1/types/echo.py | 591 - .../google/showcase_v1beta1/types/identity.py | 255 - .../showcase_v1beta1/types/messaging.py | 668 - .../generated_showcase/noxfile.py | 635 - ...7469_v1beta1_generated_echo_block_async.py | 51 - ...:7469_v1beta1_generated_echo_block_sync.py | 51 - ...:7469_v1beta1_generated_echo_chat_async.py | 63 - ...t:7469_v1beta1_generated_echo_chat_sync.py | 63 - ...69_v1beta1_generated_echo_collect_async.py | 62 - ...469_v1beta1_generated_echo_collect_sync.py | 62 - ...:7469_v1beta1_generated_echo_echo_async.py | 52 - ...generated_echo_echo_error_details_async.py | 51 - ..._generated_echo_echo_error_details_sync.py | 51 - ...t:7469_v1beta1_generated_echo_echo_sync.py | 52 - ...469_v1beta1_generated_echo_expand_async.py | 52 - ...7469_v1beta1_generated_echo_expand_sync.py | 52 - ...beta1_generated_echo_paged_expand_async.py | 53 - ...enerated_echo_paged_expand_legacy_async.py | 53 - ...d_echo_paged_expand_legacy_mapped_async.py | 53 - ...ed_echo_paged_expand_legacy_mapped_sync.py | 53 - ...generated_echo_paged_expand_legacy_sync.py | 53 - ...1beta1_generated_echo_paged_expand_sync.py | 53 - ...:7469_v1beta1_generated_echo_wait_async.py | 55 - ...t:7469_v1beta1_generated_echo_wait_sync.py | 55 - ...a1_generated_identity_create_user_async.py | 51 - ...ta1_generated_identity_create_user_sync.py | 51 - ...a1_generated_identity_delete_user_async.py | 50 - ...ta1_generated_identity_delete_user_sync.py | 50 - ...beta1_generated_identity_get_user_async.py | 52 - ...1beta1_generated_identity_get_user_sync.py | 52 - ...ta1_generated_identity_list_users_async.py | 52 - ...eta1_generated_identity_list_users_sync.py | 52 - ...a1_generated_identity_update_user_async.py | 51 - ...ta1_generated_identity_update_user_sync.py | 51 - ...beta1_generated_messaging_connect_async.py | 62 - ...1beta1_generated_messaging_connect_sync.py | 62 - ..._generated_messaging_create_blurb_async.py | 52 - ...1_generated_messaging_create_blurb_sync.py | 52 - ...1_generated_messaging_create_room_async.py | 51 - ...a1_generated_messaging_create_room_sync.py | 51 - ..._generated_messaging_delete_blurb_async.py | 50 - ...1_generated_messaging_delete_blurb_sync.py | 50 - ...1_generated_messaging_delete_room_async.py | 50 - ...a1_generated_messaging_delete_room_sync.py | 50 - ...ta1_generated_messaging_get_blurb_async.py | 52 - ...eta1_generated_messaging_get_blurb_sync.py | 52 - ...eta1_generated_messaging_get_room_async.py | 52 - ...beta1_generated_messaging_get_room_sync.py | 52 - ...1_generated_messaging_list_blurbs_async.py | 53 - ...a1_generated_messaging_list_blurbs_sync.py | 53 - ...a1_generated_messaging_list_rooms_async.py | 52 - ...ta1_generated_messaging_list_rooms_sync.py | 52 - ...generated_messaging_search_blurbs_async.py | 56 - ..._generated_messaging_search_blurbs_sync.py | 56 - ...1_generated_messaging_send_blurbs_async.py | 62 - ...a1_generated_messaging_send_blurbs_sync.py | 62 - ...generated_messaging_stream_blurbs_async.py | 53 - ..._generated_messaging_stream_blurbs_sync.py | 53 - ..._generated_messaging_update_blurb_async.py | 51 - ...1_generated_messaging_update_blurb_sync.py | 51 - ...1_generated_messaging_update_room_async.py | 51 - ...a1_generated_messaging_update_room_sync.py | 51 - ...ppet_metadata_google.showcase.v1beta1.json | 4618 ------ .../generated_showcase/setup.py | 101 - .../generated_showcase/showcase.desc | Bin 260515 -> 0 bytes .../showcase_grpc_service_config.json | 90 - .../generated_showcase/showcase_v1beta1.yaml | 91 - .../testing/constraints-3.10.txt | 12 - .../testing/constraints-3.11.txt | 11 - .../testing/constraints-3.12.txt | 11 - .../testing/constraints-3.13.txt | 13 - .../testing/constraints-3.14.txt | 13 - .../testing/constraints-3.15.txt | 13 - .../generated_showcase/tests/__init__.py | 16 - .../generated_showcase/tests/unit/__init__.py | 16 - .../tests/unit/gapic/__init__.py | 16 - .../unit/gapic/showcase_v1beta1/__init__.py | 16 - .../unit/gapic/showcase_v1beta1/test_echo.py | 9408 ------------ .../gapic/showcase_v1beta1/test_identity.py | 6950 --------- .../gapic/showcase_v1beta1/test_messaging.py | 11873 ---------------- packages/gapic-generator/noxfile.py | 43 +- 138 files changed, 26 insertions(+), 70728 deletions(-) delete mode 100644 packages/gapic-generator/generated_showcase/.coveragerc delete mode 100644 packages/gapic-generator/generated_showcase/.flake8 delete mode 100644 packages/gapic-generator/generated_showcase/LICENSE delete mode 100644 packages/gapic-generator/generated_showcase/MANIFEST.in delete mode 100644 packages/gapic-generator/generated_showcase/README.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/_static/custom.css delete mode 100644 packages/gapic-generator/generated_showcase/docs/_templates/layout.html delete mode 100644 packages/gapic-generator/generated_showcase/docs/conf.py delete mode 100644 packages/gapic-generator/generated_showcase/docs/index.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/multiprocessing.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst delete mode 100644 packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase/py.typed delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py delete mode 100644 packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py delete mode 100644 packages/gapic-generator/generated_showcase/noxfile.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py delete mode 100644 packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json delete mode 100644 packages/gapic-generator/generated_showcase/setup.py delete mode 100644 packages/gapic-generator/generated_showcase/showcase.desc delete mode 100644 packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json delete mode 100644 packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml delete mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt delete mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt delete mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt delete mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt delete mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt delete mode 100644 packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt delete mode 100644 packages/gapic-generator/generated_showcase/tests/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/tests/unit/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py delete mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py delete mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py delete mode 100644 packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py diff --git a/packages/gapic-generator/generated_showcase/.coveragerc b/packages/gapic-generator/generated_showcase/.coveragerc deleted file mode 100644 index 55f3b8c4ec27..000000000000 --- a/packages/gapic-generator/generated_showcase/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/showcase/__init__.py - google/showcase/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/packages/gapic-generator/generated_showcase/.flake8 b/packages/gapic-generator/generated_showcase/.flake8 deleted file mode 100644 index f9069a84687b..000000000000 --- a/packages/gapic-generator/generated_showcase/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/packages/gapic-generator/generated_showcase/LICENSE b/packages/gapic-generator/generated_showcase/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/packages/gapic-generator/generated_showcase/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/packages/gapic-generator/generated_showcase/MANIFEST.in b/packages/gapic-generator/generated_showcase/MANIFEST.in deleted file mode 100644 index f932577add9d..000000000000 --- a/packages/gapic-generator/generated_showcase/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/packages/gapic-generator/generated_showcase/README.rst b/packages/gapic-generator/generated_showcase/README.rst deleted file mode 100644 index 4e6b807730d9..000000000000 --- a/packages/gapic-generator/generated_showcase/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Showcase 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 Showcase 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 - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/packages/gapic-generator/generated_showcase/docs/_static/custom.css b/packages/gapic-generator/generated_showcase/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/packages/gapic-generator/generated_showcase/docs/_templates/layout.html b/packages/gapic-generator/generated_showcase/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/packages/gapic-generator/generated_showcase/docs/conf.py b/packages/gapic-generator/generated_showcase/docs/conf.py deleted file mode 100644 index 1b373c50bdd8..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/conf.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-showcase 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 logging -import os -import shlex -import sys -import logging -from typing import Any - -# 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("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# 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.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -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-showcase" -copyright = u"2026, Google, LLC" -author = u"Google APIs" - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [ - "_build", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# 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 Client Libraries for google-showcase", - "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-showcase-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-showcase.tex", - u"google-showcase 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-showcase", - "google-showcase 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-showcase", - "google-showcase Documentation", - author, - "google-showcase", - "google-showcase Library", - "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": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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 - -# Setup for sphinx behaviors such as warning filters. -class UnexpectedUnindentFilter(logging.Filter): - """Filter out warnings about unexpected unindentation following bullet lists.""" - - def filter(self, record: logging.LogRecord) -> bool: - """Filter the log record. - - Args: - record (logging.LogRecord): The log record. - - Returns: - bool: False to suppress the warning, True to allow it. - """ - msg = record.getMessage() - if "Bullet list ends without a blank line" in msg: - return False - return True - - -def setup(app: Any) -> None: - """Setup the Sphinx application. - - Args: - app (Any): The Sphinx application. - """ - # Sphinx's logger is hierarchical. Adding a filter to the - # root 'sphinx' logger will catch warnings from all sub-loggers. - logger = logging.getLogger('sphinx') - logger.addFilter(UnexpectedUnindentFilter()) diff --git a/packages/gapic-generator/generated_showcase/docs/index.rst b/packages/gapic-generator/generated_showcase/docs/index.rst deleted file mode 100644 index 272113be4cd4..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - showcase_v1beta1/services_ - showcase_v1beta1/types_ diff --git a/packages/gapic-generator/generated_showcase/docs/multiprocessing.rst b/packages/gapic-generator/generated_showcase/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst deleted file mode 100644 index 654e25afb43e..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/echo.rst +++ /dev/null @@ -1,10 +0,0 @@ -Echo ----------------------- - -.. automodule:: google.showcase_v1beta1.services.echo - :members: - :inherited-members: - -.. automodule:: google.showcase_v1beta1.services.echo.pagers - :members: - :inherited-members: diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst deleted file mode 100644 index 37affa6718e6..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/identity.rst +++ /dev/null @@ -1,10 +0,0 @@ -Identity --------------------------- - -.. automodule:: google.showcase_v1beta1.services.identity - :members: - :inherited-members: - -.. automodule:: google.showcase_v1beta1.services.identity.pagers - :members: - :inherited-members: diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst deleted file mode 100644 index 34ee90be489d..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/messaging.rst +++ /dev/null @@ -1,10 +0,0 @@ -Messaging ---------------------------- - -.. automodule:: google.showcase_v1beta1.services.messaging - :members: - :inherited-members: - -.. automodule:: google.showcase_v1beta1.services.messaging.pagers - :members: - :inherited-members: diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst deleted file mode 100644 index 348915d7ea57..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/services_.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Showcase v1beta1 API -======================================== -.. toctree:: - :maxdepth: 2 - - echo - identity - messaging diff --git a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst b/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst deleted file mode 100644 index ad3d8ea4fe27..000000000000 --- a/packages/gapic-generator/generated_showcase/docs/showcase_v1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Showcase v1beta1 API -===================================== - -.. automodule:: google.showcase_v1beta1.types - :members: - :show-inheritance: diff --git a/packages/gapic-generator/generated_showcase/google/showcase/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase/__init__.py deleted file mode 100644 index 13c5d82c9928..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase/__init__.py +++ /dev/null @@ -1,127 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.showcase_v1beta1.services.echo.client import EchoClient -from google.showcase_v1beta1.services.echo.async_client import EchoAsyncClient -from google.showcase_v1beta1.services.identity.client import IdentityClient -from google.showcase_v1beta1.services.identity.async_client import IdentityAsyncClient -from google.showcase_v1beta1.services.messaging.client import MessagingClient -from google.showcase_v1beta1.services.messaging.async_client import MessagingAsyncClient - -from google.showcase_v1beta1.types.echo import BlockRequest -from google.showcase_v1beta1.types.echo import BlockResponse -from google.showcase_v1beta1.types.echo import EchoErrorDetailsRequest -from google.showcase_v1beta1.types.echo import EchoErrorDetailsResponse -from google.showcase_v1beta1.types.echo import EchoRequest -from google.showcase_v1beta1.types.echo import EchoResponse -from google.showcase_v1beta1.types.echo import ErrorWithMultipleDetails -from google.showcase_v1beta1.types.echo import ErrorWithSingleDetail -from google.showcase_v1beta1.types.echo import ExpandRequest -from google.showcase_v1beta1.types.echo import PagedExpandLegacyMappedResponse -from google.showcase_v1beta1.types.echo import PagedExpandLegacyRequest -from google.showcase_v1beta1.types.echo import PagedExpandRequest -from google.showcase_v1beta1.types.echo import PagedExpandResponse -from google.showcase_v1beta1.types.echo import PagedExpandResponseList -from google.showcase_v1beta1.types.echo import WaitMetadata -from google.showcase_v1beta1.types.echo import WaitRequest -from google.showcase_v1beta1.types.echo import WaitResponse -from google.showcase_v1beta1.types.echo import Severity -from google.showcase_v1beta1.types.identity import CreateUserRequest -from google.showcase_v1beta1.types.identity import DeleteUserRequest -from google.showcase_v1beta1.types.identity import GetUserRequest -from google.showcase_v1beta1.types.identity import ListUsersRequest -from google.showcase_v1beta1.types.identity import ListUsersResponse -from google.showcase_v1beta1.types.identity import UpdateUserRequest -from google.showcase_v1beta1.types.identity import User -from google.showcase_v1beta1.types.messaging import Blurb -from google.showcase_v1beta1.types.messaging import ConnectRequest -from google.showcase_v1beta1.types.messaging import CreateBlurbRequest -from google.showcase_v1beta1.types.messaging import CreateRoomRequest -from google.showcase_v1beta1.types.messaging import DeleteBlurbRequest -from google.showcase_v1beta1.types.messaging import DeleteRoomRequest -from google.showcase_v1beta1.types.messaging import GetBlurbRequest -from google.showcase_v1beta1.types.messaging import GetRoomRequest -from google.showcase_v1beta1.types.messaging import ListBlurbsRequest -from google.showcase_v1beta1.types.messaging import ListBlurbsResponse -from google.showcase_v1beta1.types.messaging import ListRoomsRequest -from google.showcase_v1beta1.types.messaging import ListRoomsResponse -from google.showcase_v1beta1.types.messaging import Room -from google.showcase_v1beta1.types.messaging import SearchBlurbsMetadata -from google.showcase_v1beta1.types.messaging import SearchBlurbsRequest -from google.showcase_v1beta1.types.messaging import SearchBlurbsResponse -from google.showcase_v1beta1.types.messaging import SendBlurbsResponse -from google.showcase_v1beta1.types.messaging import StreamBlurbsRequest -from google.showcase_v1beta1.types.messaging import StreamBlurbsResponse -from google.showcase_v1beta1.types.messaging import UpdateBlurbRequest -from google.showcase_v1beta1.types.messaging import UpdateRoomRequest - -__all__ = ('EchoClient', - 'EchoAsyncClient', - 'IdentityClient', - 'IdentityAsyncClient', - 'MessagingClient', - 'MessagingAsyncClient', - 'BlockRequest', - 'BlockResponse', - 'EchoErrorDetailsRequest', - 'EchoErrorDetailsResponse', - 'EchoRequest', - 'EchoResponse', - 'ErrorWithMultipleDetails', - 'ErrorWithSingleDetail', - 'ExpandRequest', - 'PagedExpandLegacyMappedResponse', - 'PagedExpandLegacyRequest', - 'PagedExpandRequest', - 'PagedExpandResponse', - 'PagedExpandResponseList', - 'WaitMetadata', - 'WaitRequest', - 'WaitResponse', - 'Severity', - 'CreateUserRequest', - 'DeleteUserRequest', - 'GetUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - 'UpdateUserRequest', - 'User', - 'Blurb', - 'ConnectRequest', - 'CreateBlurbRequest', - 'CreateRoomRequest', - 'DeleteBlurbRequest', - 'DeleteRoomRequest', - 'GetBlurbRequest', - 'GetRoomRequest', - 'ListBlurbsRequest', - 'ListBlurbsResponse', - 'ListRoomsRequest', - 'ListRoomsResponse', - 'Room', - 'SearchBlurbsMetadata', - 'SearchBlurbsRequest', - 'SearchBlurbsResponse', - 'SendBlurbsResponse', - 'StreamBlurbsRequest', - 'StreamBlurbsResponse', - 'UpdateBlurbRequest', - 'UpdateRoomRequest', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py b/packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py deleted file mode 100644 index e89a0031d71b..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/google/showcase/py.typed b/packages/gapic-generator/generated_showcase/google/showcase/py.typed deleted file mode 100644 index 22eee9858aaf..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-showcase package uses inline types. diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py deleted file mode 100644 index 47ab3dc442fb..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/__init__.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1 import gapic_version as package_version - -import google.api_core as api_core -import sys - -__version__ = package_version.__version__ - -from importlib import metadata - -# PEP 0810: Explicit Lazy Imports -# Python 3.15+ natively intercepts and defers these imports. -# Developers can disable this behavior and force eager imports. -# For more information, see: -# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter -# Older Python versions safely ignore this variable. -__lazy_modules__ = { -"google.showcase_v1beta1.services.echo", -"google.showcase_v1beta1.services.identity", -"google.showcase_v1beta1.services.messaging", -"google.showcase_v1beta1.types.echo", -"google.showcase_v1beta1.types.identity", -"google.showcase_v1beta1.types.messaging", -} - - -from .services.echo import EchoClient -from .services.echo import EchoAsyncClient -from .services.identity import IdentityClient -from .services.identity import IdentityAsyncClient -from .services.messaging import MessagingClient -from .services.messaging import MessagingAsyncClient - -from .types.echo import BlockRequest -from .types.echo import BlockResponse -from .types.echo import EchoErrorDetailsRequest -from .types.echo import EchoErrorDetailsResponse -from .types.echo import EchoRequest -from .types.echo import EchoResponse -from .types.echo import ErrorWithMultipleDetails -from .types.echo import ErrorWithSingleDetail -from .types.echo import ExpandRequest -from .types.echo import PagedExpandLegacyMappedResponse -from .types.echo import PagedExpandLegacyRequest -from .types.echo import PagedExpandRequest -from .types.echo import PagedExpandResponse -from .types.echo import PagedExpandResponseList -from .types.echo import WaitMetadata -from .types.echo import WaitRequest -from .types.echo import WaitResponse -from .types.echo import Severity -from .types.identity import CreateUserRequest -from .types.identity import DeleteUserRequest -from .types.identity import GetUserRequest -from .types.identity import ListUsersRequest -from .types.identity import ListUsersResponse -from .types.identity import UpdateUserRequest -from .types.identity import User -from .types.messaging import Blurb -from .types.messaging import ConnectRequest -from .types.messaging import CreateBlurbRequest -from .types.messaging import CreateRoomRequest -from .types.messaging import DeleteBlurbRequest -from .types.messaging import DeleteRoomRequest -from .types.messaging import GetBlurbRequest -from .types.messaging import GetRoomRequest -from .types.messaging import ListBlurbsRequest -from .types.messaging import ListBlurbsResponse -from .types.messaging import ListRoomsRequest -from .types.messaging import ListRoomsResponse -from .types.messaging import Room -from .types.messaging import SearchBlurbsMetadata -from .types.messaging import SearchBlurbsRequest -from .types.messaging import SearchBlurbsResponse -from .types.messaging import SendBlurbsResponse -from .types.messaging import StreamBlurbsRequest -from .types.messaging import StreamBlurbsResponse -from .types.messaging import UpdateBlurbRequest -from .types.messaging import UpdateRoomRequest - -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.showcase_v1beta1") # type: ignore - api_core.check_dependency_versions("google.showcase_v1beta1") # type: ignore -else: # pragma: NO COVER - # An older version of api_core is installed which does not define the - # functions above. We do equivalent checks manually. - try: - import warnings - - _py_version_str = sys.version.split()[0] - _package_label = "google.showcase_v1beta1" - if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) - - def parse_version_to_tuple(version_string: str): - """Safely converts a semantic version string to a comparable tuple of integers. - Example: "6.33.5" -> (6, 33, 5) - Ignores non-numeric parts and handles common version formats. - Args: - version_string: Version string in the format "x.y.z" or "x.y.z" - Returns: - Tuple of integers for the parsed version string. - """ - parts = [] - for part in version_string.split("."): - try: - parts.append(int(part)) - except ValueError: - # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. - # This is a simplification compared to 'packaging.parse_version', but sufficient - # for comparing strictly numeric semantic versions. - break - return tuple(parts) - - def _get_version(dependency_name): - try: - version_string: str = metadata.version(dependency_name) - parsed_version = parse_version_to_tuple(version_string) - return (parsed_version, version_string) - except Exception: - # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) - # or errors during parse_version_to_tuple - return (None, "--") - - _dependency_package = "google.protobuf" - _next_supported_version = "6.33.5" - _next_supported_version_tuple = (6, 33, 5) - _recommendation = " (we recommend 7.x)" - (_version_used, _version_used_string) = _get_version(_dependency_package) - if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) - except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") - -__all__ = ( - 'EchoAsyncClient', - 'IdentityAsyncClient', - 'MessagingAsyncClient', -'BlockRequest', -'BlockResponse', -'Blurb', -'ConnectRequest', -'CreateBlurbRequest', -'CreateRoomRequest', -'CreateUserRequest', -'DeleteBlurbRequest', -'DeleteRoomRequest', -'DeleteUserRequest', -'EchoClient', -'EchoErrorDetailsRequest', -'EchoErrorDetailsResponse', -'EchoRequest', -'EchoResponse', -'ErrorWithMultipleDetails', -'ErrorWithSingleDetail', -'ExpandRequest', -'GetBlurbRequest', -'GetRoomRequest', -'GetUserRequest', -'IdentityClient', -'ListBlurbsRequest', -'ListBlurbsResponse', -'ListRoomsRequest', -'ListRoomsResponse', -'ListUsersRequest', -'ListUsersResponse', -'MessagingClient', -'PagedExpandLegacyMappedResponse', -'PagedExpandLegacyRequest', -'PagedExpandRequest', -'PagedExpandResponse', -'PagedExpandResponseList', -'Room', -'SearchBlurbsMetadata', -'SearchBlurbsRequest', -'SearchBlurbsResponse', -'SendBlurbsResponse', -'Severity', -'StreamBlurbsRequest', -'StreamBlurbsResponse', -'UpdateBlurbRequest', -'UpdateRoomRequest', -'UpdateUserRequest', -'User', -'WaitMetadata', -'WaitRequest', -'WaitResponse', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py deleted file mode 100644 index dd6a5824d373..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/_compat.py +++ /dev/null @@ -1,108 +0,0 @@ -# # Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, Dict, List, Optional, Tuple - -try: - from google.api_core.rest_helpers import ( - flatten_query_params, - transcode_request, - ) -except ImportError: # pragma: NO COVER - # TODO: Remove these fallbacks when google-api-core >= 2.18.0 is the minimum required version. - import functools - import json - import operator - from google.protobuf import json_format # type: ignore - from google.api_core import path_template # type: ignore - - def flatten_query_params(obj, strict=False): # pragma: NO COVER - if obj is not None and not isinstance(obj, dict): - raise TypeError("flatten_query_params must be called with dict object") - return _flatten(obj, key_path=[], strict=strict) - - def _flatten(obj, key_path, strict=False): # pragma: NO COVER - if obj is None: - return [] - if isinstance(obj, dict): - return _flatten_dict(obj, key_path=key_path, strict=strict) - if isinstance(obj, list): - return _flatten_list(obj, key_path=key_path, strict=strict) - return _flatten_value(obj, key_path=key_path, strict=strict) - - def _is_primitive_value(obj): # pragma: NO COVER - if obj is None: - return False - if isinstance(obj, (list, dict)): - raise ValueError("query params may not contain repeated dicts or lists") - return True - - def _flatten_value(obj, key_path, strict=False): # pragma: NO COVER - return [(".".join(key_path), _canonicalize(obj, strict=strict))] - - def _flatten_dict(obj, key_path, strict=False): # pragma: NO COVER - items = ( - _flatten(value, key_path=key_path + [key], strict=strict) - for key, value in obj.items() - ) - return functools.reduce(operator.concat, items, []) - - def _flatten_list(elems, key_path, strict=False): # pragma: NO COVER - items = ( - _flatten_value(elem, key_path=key_path, strict=strict) - for elem in elems - if _is_primitive_value(elem) - ) - return functools.reduce(operator.concat, items, []) - - def _canonicalize(obj, strict=False): # pragma: NO COVER - if strict: - value = str(obj) - if isinstance(obj, bool): - value = value.lower() - return value - return obj - - def transcode_request( # pragma: NO COVER - http_options: List[Dict[str, str]], - request: Any, - required_fields_default_values: Optional[Dict[str, Any]] = None, - rest_numeric_enums: bool = False, - ) -> Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: - pb_request = getattr(request, "_pb", request) - transcoded_request = path_template.transcode(http_options, pb_request) - - body_json = None - if transcoded_request.get("body") is not None: - body_json = json_format.MessageToJson( - transcoded_request["body"], - use_integers_for_enums=rest_numeric_enums, - ) - - query_params_json = {} - if transcoded_request.get("query_params") is not None: - query_params_json = json.loads(json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=rest_numeric_enums, - )) - - if required_fields_default_values: - for k, v in required_fields_default_values.items(): - if k not in query_params_json: - query_params_json[k] = v - - if rest_numeric_enums: - query_params_json["$alt"] = "json;enum-encoding=int" - - return transcoded_request, body_json, query_params_json diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py deleted file mode 100644 index e89a0031d71b..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed deleted file mode 100644 index 22eee9858aaf..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-showcase package uses inline types. diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py deleted file mode 100644 index 32b36c5c4fe0..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py deleted file mode 100644 index e5b65be3966a..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 EchoClient -from .async_client import EchoAsyncClient - -__all__ = ( - 'EchoClient', - 'EchoAsyncClient', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py deleted file mode 100644 index 5ddcca846a9f..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/async_client.py +++ /dev/null @@ -1,1937 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import uuid - -from google.showcase_v1beta1 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 -import google.protobuf - -try: - from google.api_core import version_header - HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - HAS_GOOGLE_API_CORE_VERSION_HEADER = False - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.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.showcase_v1beta1.services.echo import pagers -from google.showcase_v1beta1.types import echo as gs_echo -import google.api_core.operation as operation # type: ignore -import google.api_core.operation_async as operation_async # type: ignore -import google.rpc.status_pb2 as status_pb2 # type: ignore -from .transports.base import EchoTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EchoGrpcAsyncIOTransport -from .client import EchoClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class EchoAsyncClient: - """This service is used showcase the four main types of rpcs - - unary, server side streaming, client side streaming, and - bidirectional streaming. This service also exposes methods that - explicitly implement server delay, and paginated calls. Set the - 'showcase-trailer' metadata key on any method to have the values - echoed in the response trailers. Set the 'x-goog-request-params' - metadata key on any method to have the values echoed in the - response headers. - This class implements API version v1_20240408.""" - - _client: EchoClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EchoClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EchoClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EchoClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EchoClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(EchoClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EchoClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EchoClient.common_folder_path) - parse_common_folder_path = staticmethod(EchoClient.parse_common_folder_path) - common_organization_path = staticmethod(EchoClient.common_organization_path) - parse_common_organization_path = staticmethod(EchoClient.parse_common_organization_path) - common_project_path = staticmethod(EchoClient.common_project_path) - parse_common_project_path = staticmethod(EchoClient.parse_common_project_path) - common_location_path = staticmethod(EchoClient.common_location_path) - parse_common_location_path = staticmethod(EchoClient.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: - EchoAsyncClient: The constructed client. - """ - sa_info_func = ( - EchoClient.from_service_account_info.__func__ # type: ignore - ) - return sa_info_func(EchoAsyncClient, info, *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: - EchoAsyncClient: The constructed client. - """ - sa_file_func = ( - EchoClient.from_service_account_file.__func__ # type: ignore - ) - return sa_file_func(EchoAsyncClient, filename, *args, **kwargs) - - 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 EchoClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EchoTransport: - """Returns the transport used by the client instance. - - Returns: - EchoTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self) -> str: - """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 = EchoClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EchoTransport, Callable[..., EchoTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the echo 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,EchoTransport,Callable[..., EchoTransport]]]): - 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 EchoTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - 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 = EchoClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.showcase_v1beta1.EchoAsyncClient`.", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.showcase.v1beta1.Echo", - "credentialsType": None, - } - ) - - async def echo(self, - request: Optional[Union[gs_echo.EchoRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.EchoResponse: - r"""This method simply echoes the request. This method - showcases unary RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_echo(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # Make the request - response = await client.echo(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.EchoRequest, dict]]): - The request object. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.EchoResponse: - The response message for the Echo - methods. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.EchoRequest): - request = gs_echo.EchoRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.echo] - - header_params = {} - - if request.header: - header_params["header"] = request.header - - routing_param_regex = re.compile('^(?P.*)$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("routing_id"): - header_params["routing_id"] = regex_match.group("routing_id") - - routing_param_regex = re.compile('^(?Pregions/[^/]+/zones/[^/]+(?:/.*)?)$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("table_name"): - header_params["table_name"] = regex_match.group("table_name") - - routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("super_id"): - header_params["super_id"] = regex_match.group("super_id") - - routing_param_regex = re.compile('^(?Pprojects/[^/]+/instances/[^/]+(?:/.*)?)$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("table_name"): - header_params["table_name"] = regex_match.group("table_name") - - routing_param_regex = re.compile('^projects/[^/]+/(?Pinstances/[^/]+)(?:/.*)?$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("instance_id"): - header_params["instance_id"] = regex_match.group("instance_id") - - routing_param_regex = re.compile('^(?P.*)$') - regex_match = routing_param_regex.match(request.other_header) - if regex_match and regex_match.group("baz"): - header_params["baz"] = regex_match.group("baz") - - routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') - regex_match = routing_param_regex.match(request.other_header) - if regex_match and regex_match.group("qux"): - header_params["qux"] = regex_match.group("qux") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - self._client._setup_request_id(request, 'request_id', False) - self._client._setup_request_id(request, 'other_request_id', True) - - # 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 echo_error_details(self, - request: Optional[Union[gs_echo.EchoErrorDetailsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.EchoErrorDetailsResponse: - r"""This method returns error details in a repeated - "google.protobuf.Any" field. This method showcases handling - errors thus encoded, particularly over REST transport. Note that - GAPICs only allow the type "google.protobuf.Any" for field paths - ending in "error.details", and, at run-time, the actual types - for these fields must be one of the types in - google/rpc/error_details.proto. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_echo_error_details(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoErrorDetailsRequest( - ) - - # Make the request - response = await client.echo_error_details(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.EchoErrorDetailsRequest, dict]]): - The request object. The request message used for the - EchoErrorDetails method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.EchoErrorDetailsResponse: - The response message used for the - EchoErrorDetails method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.EchoErrorDetailsRequest): - request = gs_echo.EchoErrorDetailsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.echo_error_details] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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 - - def expand(self, - request: Optional[Union[gs_echo.ExpandRequest, dict]] = None, - *, - content: Optional[str] = None, - error: Optional[status_pb2.Status] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[gs_echo.EchoResponse]]: - r"""This method splits the given content into words and - will pass each word back through the stream. This method - showcases server-side streaming RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_expand(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ExpandRequest( - ) - - # Make the request - stream = await client.expand(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.ExpandRequest, dict]]): - The request object. The request message for the Expand - method. - content (:class:`str`): - The content that will be split into - words and returned on the stream. - - This corresponds to the ``content`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - error (:class:`google.rpc.status_pb2.Status`): - The error that is thrown after all - words are sent on the stream. - - This corresponds to the ``error`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - AsyncIterable[google.showcase_v1beta1.types.EchoResponse]: - The response message for the Echo - methods. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [content, error] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.ExpandRequest): - request = gs_echo.ExpandRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if content is not None: - request.content = content - if error is not None: - request.error = error - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.expand] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect(self, - requests: Optional[AsyncIterator[gs_echo.EchoRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.EchoResponse: - r"""This method will collect the words given to it. When - the stream is closed by the client, this method will - return the a concatenation of the strings passed to it. - This method showcases client-side streaming RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_collect(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = await client.collect(requests=request_generator()) - - # Handle the response - print(response) - - Args: - requests (AsyncIterator[`google.showcase_v1beta1.types.EchoRequest`]): - The request object AsyncIterator. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.EchoResponse: - The response message for the Echo - methods. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.collect] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def chat(self, - requests: Optional[AsyncIterator[gs_echo.EchoRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[gs_echo.EchoResponse]]: - r"""This method, upon receiving a request on the stream, - will pass the same content back on the stream. This - method showcases bidirectional streaming RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_chat(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.chat(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.showcase_v1beta1.types.EchoRequest`]): - The request object AsyncIterator. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - AsyncIterable[google.showcase_v1beta1.types.EchoResponse]: - The response message for the Echo - methods. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.chat] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def paged_expand(self, - request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.PagedExpandAsyncPager: - r"""This is similar to the Expand method but instead of - returning a stream of expanded words, this method - returns a paged list of expanded words. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_paged_expand(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]]): - The request object. The request for the PagedExpand - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.echo.pagers.PagedExpandAsyncPager: - The response for the PagedExpand - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.PagedExpandRequest): - request = gs_echo.PagedExpandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.paged_expand] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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.PagedExpandAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def paged_expand_legacy(self, - request: Optional[Union[gs_echo.PagedExpandLegacyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.PagedExpandLegacyAsyncPager: - r"""This is similar to the PagedExpand except that it uses - max_results instead of page_size, as some legacy APIs still do. - New APIs should NOT use this pattern. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_paged_expand_legacy(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandLegacyRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.PagedExpandLegacyRequest, dict]]): - The request object. The request for the PagedExpandLegacy - method. This is a pattern used by some - legacy APIs. New APIs should NOT use - this pattern, but rather something like - PagedExpandRequest which conforms to - aip.dev/158. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyAsyncPager: - The response for the PagedExpand - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.PagedExpandLegacyRequest): - request = gs_echo.PagedExpandLegacyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.paged_expand_legacy] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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.PagedExpandLegacyAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def paged_expand_legacy_mapped(self, - request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.PagedExpandLegacyMappedAsyncPager: - r"""This method returns a map containing lists of words that appear - in the input, keyed by their initial character. The only words - returned are the ones included in the current page, as - determined by page_token and page_size, which both refer to the - word indices in the input. This paging result consisting of a - map of lists is a pattern used by some legacy APIs. New APIs - should NOT use this pattern. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_paged_expand_legacy_mapped(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy_mapped(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]]): - The request object. The request for the PagedExpand - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedAsyncPager: - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.PagedExpandRequest): - request = gs_echo.PagedExpandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.paged_expand_legacy_mapped] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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.PagedExpandLegacyMappedAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def wait(self, - request: Optional[Union[gs_echo.WaitRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""This method will wait for the requested amount of - time and then return. This method showcases how a client - handles a request timeout. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_wait(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.WaitRequest( - ) - - # Make the request - operation = await client.wait(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.WaitRequest, dict]]): - The request object. The request for Wait method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.showcase_v1beta1.types.WaitResponse` The - result of the Wait operation. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.WaitRequest): - request = gs_echo.WaitRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.wait] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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, - gs_echo.WaitResponse, - metadata_type=gs_echo.WaitMetadata, - ) - - # Done; return the response. - return response - - async def block(self, - request: Optional[Union[gs_echo.BlockRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.BlockResponse: - r"""This method will block (wait) for the requested - amount of time and then return the response or error. - This method showcases how a client handles delays or - retries. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_block(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.BlockRequest( - ) - - # Make the request - response = await client.block(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.BlockRequest, dict]]): - The request object. The request for Block method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.BlockResponse: - The response for Block method. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.BlockRequest): - request = gs_echo.BlockRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.block] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.DeleteOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.DeleteOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.CancelOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.CancelOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.SetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.GetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.TestIamPermissionsRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.GetLocationRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.GetLocationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.ListLocationsRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.ListLocationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "EchoAsyncClient": - 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__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "EchoAsyncClient", -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py deleted file mode 100644 index 5f5f09827e7c..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/client.py +++ /dev/null @@ -1,2361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast -import uuid -import warnings - -from google.showcase_v1beta1 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 -import google.protobuf -try: - from google.api_core import version_header - HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - HAS_GOOGLE_API_CORE_VERSION_HEADER = False - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.cloud.location import locations_pb2 # type: ignore -from google.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.showcase_v1beta1.services.echo import pagers -from google.showcase_v1beta1.types import echo as gs_echo -import google.api_core.operation as operation # type: ignore -import google.api_core.operation_async as operation_async # type: ignore -import google.rpc.status_pb2 as status_pb2 # type: ignore -from .transports.base import EchoTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EchoGrpcTransport -from .transports.grpc_asyncio import EchoGrpcAsyncIOTransport -from .transports.rest import EchoRestTransport - - -class EchoClientMeta(type): - """Metaclass for the Echo 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[EchoTransport]] - _transport_registry["grpc"] = EchoGrpcTransport - _transport_registry["grpc_asyncio"] = EchoGrpcAsyncIOTransport - _transport_registry["rest"] = EchoRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EchoTransport]: - """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 EchoClient(metaclass=EchoClientMeta): - """This service is used showcase the four main types of rpcs - - unary, server side streaming, client side streaming, and - bidirectional streaming. This service also exposes methods that - explicitly implement server delay, and paginated calls. Set the - 'showcase-trailer' metadata key on any method to have the values - echoed in the response trailers. Set the 'x-goog-request-params' - metadata key on any method to have the values echoed in the - response headers. - This class implements API version v1_20240408.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: - """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: - Optional[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) - if m is None: - # Could not parse api_endpoint; return as-is. - return 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 = "localhost:7469" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "localhost:7469" - _DEFAULT_UNIVERSE = "googleapis.com" - - @staticmethod - def _use_client_cert_effective(): - """Returns whether client certificate should be used for mTLS if the - google-auth version supports should_use_client_cert automatic mTLS enablement. - - Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. - - Returns: - bool: whether client certificate should be used for mTLS - Raises: - ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) - """ - # check if google-auth version supports should_use_client_cert for automatic mTLS enablement - if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER - return mtls.should_use_client_cert() - else: # pragma: NO COVER - # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - if use_client_cert_str not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" - " either `true` or `false`" - ) - return use_client_cert_str == "true" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EchoClient: 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: - EchoClient: 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) -> EchoTransport: - """Returns the transport used by the client instance. - - Returns: - EchoTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = EchoClient._use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = EchoClient._use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert, use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: - """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 = EchoClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EchoClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EchoClient._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 = EchoClient._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 - - @staticmethod - def _setup_request_id(request, field_name: str, is_proto3_optional: bool): - """Populate a UUID4 field in the request if it is not already set. - - Args: - request (Union[google.protobuf.message.Message, dict]): The request object. - field_name (str): The name of the field to populate. - is_proto3_optional (bool): Whether the field is proto3 optional. - """ - if isinstance(request, dict): - if is_proto3_optional: - if field_name not in request: - request[field_name] = str(uuid.uuid4()) - elif not request.get(field_name): - request[field_name] = str(uuid.uuid4()) - return - - if is_proto3_optional: - try: - # Pure protobuf messages - if not request.HasField(field_name): - setattr(request, field_name, str(uuid.uuid4())) - except (AttributeError, ValueError): - # Proto-plus messages or other objects - if field_name not in request: - setattr(request, field_name, str(uuid.uuid4())) - else: - if not getattr(request, field_name): - setattr(request, field_name, str(uuid.uuid4())) - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self) -> str: - """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, EchoTransport, Callable[..., EchoTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the echo client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. 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,EchoTransport,Callable[..., EchoTransport]]]): - 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 EchoTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - 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 = EchoClient._read_environment_variables() - self._client_cert_source = EchoClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EchoClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint: str = "" # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, EchoTransport) - if transport_provided: - # transport is a EchoTransport 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(EchoTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EchoClient._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[EchoTransport], Callable[..., EchoTransport]] = ( - EchoClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EchoTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.showcase_v1beta1.EchoClient`.", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.showcase.v1beta1.Echo", - "credentialsType": None, - } - ) - - def echo(self, - request: Optional[Union[gs_echo.EchoRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.EchoResponse: - r"""This method simply echoes the request. This method - showcases unary RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_echo(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # Make the request - response = client.echo(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.EchoRequest, dict]): - The request object. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.EchoResponse: - The response message for the Echo - methods. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.EchoRequest): - request = gs_echo.EchoRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.echo] - - header_params = {} - - if request.header: - header_params["header"] = request.header - - routing_param_regex = re.compile('^(?P.*)$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("routing_id"): - header_params["routing_id"] = regex_match.group("routing_id") - - routing_param_regex = re.compile('^(?Pregions/[^/]+/zones/[^/]+(?:/.*)?)$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("table_name"): - header_params["table_name"] = regex_match.group("table_name") - - routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("super_id"): - header_params["super_id"] = regex_match.group("super_id") - - routing_param_regex = re.compile('^(?Pprojects/[^/]+/instances/[^/]+(?:/.*)?)$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("table_name"): - header_params["table_name"] = regex_match.group("table_name") - - routing_param_regex = re.compile('^projects/[^/]+/(?Pinstances/[^/]+)(?:/.*)?$') - regex_match = routing_param_regex.match(request.header) - if regex_match and regex_match.group("instance_id"): - header_params["instance_id"] = regex_match.group("instance_id") - - routing_param_regex = re.compile('^(?P.*)$') - regex_match = routing_param_regex.match(request.other_header) - if regex_match and regex_match.group("baz"): - header_params["baz"] = regex_match.group("baz") - - routing_param_regex = re.compile('^(?Pprojects/[^/]+)(?:/.*)?$') - regex_match = routing_param_regex.match(request.other_header) - if regex_match and regex_match.group("qux"): - header_params["qux"] = regex_match.group("qux") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - self._setup_request_id(request, 'request_id', False) - self._setup_request_id(request, 'other_request_id', True) - - # 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 echo_error_details(self, - request: Optional[Union[gs_echo.EchoErrorDetailsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.EchoErrorDetailsResponse: - r"""This method returns error details in a repeated - "google.protobuf.Any" field. This method showcases handling - errors thus encoded, particularly over REST transport. Note that - GAPICs only allow the type "google.protobuf.Any" for field paths - ending in "error.details", and, at run-time, the actual types - for these fields must be one of the types in - google/rpc/error_details.proto. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_echo_error_details(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoErrorDetailsRequest( - ) - - # Make the request - response = client.echo_error_details(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.EchoErrorDetailsRequest, dict]): - The request object. The request message used for the - EchoErrorDetails method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.EchoErrorDetailsResponse: - The response message used for the - EchoErrorDetails method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.EchoErrorDetailsRequest): - request = gs_echo.EchoErrorDetailsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.echo_error_details] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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 expand(self, - request: Optional[Union[gs_echo.ExpandRequest, dict]] = None, - *, - content: Optional[str] = None, - error: Optional[status_pb2.Status] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[gs_echo.EchoResponse]: - r"""This method splits the given content into words and - will pass each word back through the stream. This method - showcases server-side streaming RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_expand(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ExpandRequest( - ) - - # Make the request - stream = client.expand(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.ExpandRequest, dict]): - The request object. The request message for the Expand - method. - content (str): - The content that will be split into - words and returned on the stream. - - This corresponds to the ``content`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - error (google.rpc.status_pb2.Status): - The error that is thrown after all - words are sent on the stream. - - This corresponds to the ``error`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - Iterable[google.showcase_v1beta1.types.EchoResponse]: - The response message for the Echo - methods. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [content, error] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.ExpandRequest): - request = gs_echo.ExpandRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if content is not None: - request.content = content - if error is not None: - request.error = error - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.expand] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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 collect(self, - requests: Optional[Iterator[gs_echo.EchoRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.EchoResponse: - r"""This method will collect the words given to it. When - the stream is closed by the client, this method will - return the a concatenation of the strings passed to it. - This method showcases client-side streaming RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_collect(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = client.collect(requests=request_generator()) - - # Handle the response - print(response) - - Args: - requests (Iterator[google.showcase_v1beta1.types.EchoRequest]): - The request object iterator. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.EchoResponse: - The response message for the Echo - methods. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def chat(self, - requests: Optional[Iterator[gs_echo.EchoRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[gs_echo.EchoResponse]: - r"""This method, upon receiving a request on the stream, - will pass the same content back on the stream. This - method showcases bidirectional streaming RPCs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_chat(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.chat(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.showcase_v1beta1.types.EchoRequest]): - The request object iterator. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - Iterable[google.showcase_v1beta1.types.EchoResponse]: - The response message for the Echo - methods. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.chat] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def paged_expand(self, - request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.PagedExpandPager: - r"""This is similar to the Expand method but instead of - returning a stream of expanded words, this method - returns a paged list of expanded words. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_paged_expand(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]): - The request object. The request for the PagedExpand - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.echo.pagers.PagedExpandPager: - The response for the PagedExpand - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.PagedExpandRequest): - request = gs_echo.PagedExpandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.paged_expand] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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.PagedExpandPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def paged_expand_legacy(self, - request: Optional[Union[gs_echo.PagedExpandLegacyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.PagedExpandLegacyPager: - r"""This is similar to the PagedExpand except that it uses - max_results instead of page_size, as some legacy APIs still do. - New APIs should NOT use this pattern. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_paged_expand_legacy(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandLegacyRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.PagedExpandLegacyRequest, dict]): - The request object. The request for the PagedExpandLegacy - method. This is a pattern used by some - legacy APIs. New APIs should NOT use - this pattern, but rather something like - PagedExpandRequest which conforms to - aip.dev/158. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyPager: - The response for the PagedExpand - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.PagedExpandLegacyRequest): - request = gs_echo.PagedExpandLegacyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.paged_expand_legacy] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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.PagedExpandLegacyPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def paged_expand_legacy_mapped(self, - request: Optional[Union[gs_echo.PagedExpandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.PagedExpandLegacyMappedPager: - r"""This method returns a map containing lists of words that appear - in the input, keyed by their initial character. The only words - returned are the ones included in the current page, as - determined by page_token and page_size, which both refer to the - word indices in the input. This paging result consisting of a - map of lists is a pattern used by some legacy APIs. New APIs - should NOT use this pattern. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_paged_expand_legacy_mapped(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy_mapped(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.PagedExpandRequest, dict]): - The request object. The request for the PagedExpand - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedPager: - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.PagedExpandRequest): - request = gs_echo.PagedExpandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.paged_expand_legacy_mapped] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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.PagedExpandLegacyMappedPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def wait(self, - request: Optional[Union[gs_echo.WaitRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""This method will wait for the requested amount of - time and then return. This method showcases how a client - handles a request timeout. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_wait(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.WaitRequest( - ) - - # Make the request - operation = client.wait(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.WaitRequest, dict]): - The request object. The request for Wait method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.showcase_v1beta1.types.WaitResponse` The - result of the Wait operation. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.WaitRequest): - request = gs_echo.WaitRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.wait] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # 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, - gs_echo.WaitResponse, - metadata_type=gs_echo.WaitMetadata, - ) - - # Done; return the response. - return response - - def block(self, - request: Optional[Union[gs_echo.BlockRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gs_echo.BlockResponse: - r"""This method will block (wait) for the requested - amount of time and then return the response or error. - This method showcases how a client handles delays or - retries. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_block(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.BlockRequest( - ) - - # Make the request - response = client.block(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.BlockRequest, dict]): - The request object. The request for Block method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.BlockResponse: - The response for Block method. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gs_echo.BlockRequest): - request = gs_echo.BlockRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.block] - - if HAS_GOOGLE_API_CORE_VERSION_HEADER: # pragma: NO COVER - metadata = tuple(metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "EchoClient": - 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_operation( - self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def delete_operation( - self, - request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.DeleteOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.DeleteOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.CancelOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.CancelOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.SetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.GetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def test_iam_permissions( - self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.TestIamPermissionsRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_location( - self, - request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.GetLocationRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.GetLocationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def list_locations( - self, - request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.ListLocationsRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.ListLocationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "EchoClient", -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py deleted file mode 100644 index 5a63f9b4d3f2..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/pagers.py +++ /dev/null @@ -1,450 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1.types import echo as gs_echo - - -class PagedExpandPager: - """A pager for iterating through ``paged_expand`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and - provides an ``__iter__`` method to iterate through its - ``responses`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``PagedExpand`` requests and continue to iterate - through the ``responses`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., gs_echo.PagedExpandResponse], - request: gs_echo.PagedExpandRequest, - response: gs_echo.PagedExpandResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.PagedExpandRequest): - The initial request object. - response (google.showcase_v1beta1.types.PagedExpandResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandResponse]: - 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[gs_echo.EchoResponse]: - for page in self.pages: - yield from page.responses - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class PagedExpandAsyncPager: - """A pager for iterating through ``paged_expand`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``responses`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``PagedExpand`` requests and continue to iterate - through the ``responses`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` - attributes are available on the 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[gs_echo.PagedExpandResponse]], - request: gs_echo.PagedExpandRequest, - response: gs_echo.PagedExpandResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.PagedExpandRequest): - The initial request object. - response (google.showcase_v1beta1.types.PagedExpandResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandResponse]: - 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[gs_echo.EchoResponse]: - async def async_generator(): - async for page in self.pages: - for response in page.responses: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class PagedExpandLegacyPager: - """A pager for iterating through ``paged_expand_legacy`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and - provides an ``__iter__`` method to iterate through its - ``responses`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``PagedExpandLegacy`` requests and continue to iterate - through the ``responses`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., gs_echo.PagedExpandResponse], - request: gs_echo.PagedExpandLegacyRequest, - response: gs_echo.PagedExpandResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.PagedExpandLegacyRequest): - The initial request object. - response (google.showcase_v1beta1.types.PagedExpandResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = gs_echo.PagedExpandLegacyRequest(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[gs_echo.PagedExpandResponse]: - 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[gs_echo.EchoResponse]: - for page in self.pages: - yield from page.responses - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class PagedExpandLegacyAsyncPager: - """A pager for iterating through ``paged_expand_legacy`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.PagedExpandResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``responses`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``PagedExpandLegacy`` requests and continue to iterate - through the ``responses`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.PagedExpandResponse` - attributes are available on the 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[gs_echo.PagedExpandResponse]], - request: gs_echo.PagedExpandLegacyRequest, - response: gs_echo.PagedExpandResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.PagedExpandLegacyRequest): - The initial request object. - response (google.showcase_v1beta1.types.PagedExpandResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = gs_echo.PagedExpandLegacyRequest(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[gs_echo.PagedExpandResponse]: - 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[gs_echo.EchoResponse]: - async def async_generator(): - async for page in self.pages: - for response in page.responses: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class PagedExpandLegacyMappedPager: - """A pager for iterating through ``paged_expand_legacy_mapped`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` object, and - provides an ``__iter__`` method to iterate through its - ``alphabetized`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``PagedExpandLegacyMapped`` requests and continue to iterate - through the ``alphabetized`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., gs_echo.PagedExpandLegacyMappedResponse], - request: gs_echo.PagedExpandRequest, - response: gs_echo.PagedExpandLegacyMappedResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.PagedExpandRequest): - The initial request object. - response (google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandLegacyMappedResponse]: - 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[Tuple[str, gs_echo.PagedExpandResponseList]]: - for page in self.pages: - yield from page.alphabetized.items() - - def get(self, key: str) -> Optional[gs_echo.PagedExpandResponseList]: - return self._response.alphabetized.get(key) - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class PagedExpandLegacyMappedAsyncPager: - """A pager for iterating through ``paged_expand_legacy_mapped`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``alphabetized`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``PagedExpandLegacyMapped`` requests and continue to iterate - through the ``alphabetized`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse` - attributes are available on the 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[gs_echo.PagedExpandLegacyMappedResponse]], - request: gs_echo.PagedExpandRequest, - response: gs_echo.PagedExpandLegacyMappedResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.PagedExpandRequest): - The initial request object. - response (google.showcase_v1beta1.types.PagedExpandLegacyMappedResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = gs_echo.PagedExpandRequest(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[gs_echo.PagedExpandLegacyMappedResponse]: - 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) -> Iterator[Tuple[str, gs_echo.PagedExpandResponseList]]: - async def async_generator(): - async for page in self.pages: - for response in page.alphabetized.items(): - yield response - - return async_generator() - - def get(self, key: str) -> Optional[gs_echo.PagedExpandResponseList]: - return self._response.alphabetized.get(key) - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst deleted file mode 100644 index 05bef773a754..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/README.rst +++ /dev/null @@ -1,10 +0,0 @@ - -transport inheritance structure -_______________________________ - -``EchoTransport`` is the ABC for all transports. - -- public child ``EchoGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). -- public child ``EchoGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). -- private child ``_BaseEchoRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). -- public child ``EchoRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py deleted file mode 100644 index 8a020e39cd6d..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 EchoTransport -from .grpc import EchoGrpcTransport -from .grpc_asyncio import EchoGrpcAsyncIOTransport -from .rest import EchoRestTransport -from .rest import EchoRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EchoTransport]] -_transport_registry['grpc'] = EchoGrpcTransport -_transport_registry['grpc_asyncio'] = EchoGrpcAsyncIOTransport -_transport_registry['rest'] = EchoRestTransport - -__all__ = ( - 'EchoTransport', - 'EchoGrpcTransport', - 'EchoGrpcAsyncIOTransport', - 'EchoRestTransport', - 'EchoRestInterceptor', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py deleted file mode 100644 index 1805bddee9af..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/base.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1 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 -import google.protobuf - -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.showcase_v1beta1.types import echo as gs_echo - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class EchoTransport(abc.ABC): - """Abstract transport class for Echo.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'localhost:7469' - - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - """ - - # 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) - # 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 - - self._wrapped_methods: Dict[Callable, Callable] = {} - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.echo: gapic_v1.method.wrap_method( - self.echo, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.echo_error_details: gapic_v1.method.wrap_method( - self.echo_error_details, - default_timeout=None, - client_info=client_info, - ), - self.expand: gapic_v1.method.wrap_method( - self.expand, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.collect: gapic_v1.method.wrap_method( - self.collect, - default_timeout=None, - client_info=client_info, - ), - self.chat: gapic_v1.method.wrap_method( - self.chat, - default_timeout=None, - client_info=client_info, - ), - self.paged_expand: gapic_v1.method.wrap_method( - self.paged_expand, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.paged_expand_legacy: gapic_v1.method.wrap_method( - self.paged_expand_legacy, - default_timeout=None, - client_info=client_info, - ), - self.paged_expand_legacy_mapped: gapic_v1.method.wrap_method( - self.paged_expand_legacy_mapped, - default_timeout=None, - client_info=client_info, - ), - self.wait: gapic_v1.method.wrap_method( - self.wait, - default_timeout=None, - client_info=client_info, - ), - self.block: gapic_v1.method.wrap_method( - self.block, - 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_location: gapic_v1.method.wrap_method( - self.get_location, - 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.get_iam_policy: gapic_v1.method.wrap_method( - self.get_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.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - 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, - ), - } - - 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 echo(self) -> Callable[ - [gs_echo.EchoRequest], - Union[ - gs_echo.EchoResponse, - Awaitable[gs_echo.EchoResponse] - ]]: - raise NotImplementedError() - - @property - def echo_error_details(self) -> Callable[ - [gs_echo.EchoErrorDetailsRequest], - Union[ - gs_echo.EchoErrorDetailsResponse, - Awaitable[gs_echo.EchoErrorDetailsResponse] - ]]: - raise NotImplementedError() - - @property - def expand(self) -> Callable[ - [gs_echo.ExpandRequest], - Union[ - gs_echo.EchoResponse, - Awaitable[gs_echo.EchoResponse] - ]]: - raise NotImplementedError() - - @property - def collect(self) -> Callable[ - [gs_echo.EchoRequest], - Union[ - gs_echo.EchoResponse, - Awaitable[gs_echo.EchoResponse] - ]]: - raise NotImplementedError() - - @property - def chat(self) -> Callable[ - [gs_echo.EchoRequest], - Union[ - gs_echo.EchoResponse, - Awaitable[gs_echo.EchoResponse] - ]]: - raise NotImplementedError() - - @property - def paged_expand(self) -> Callable[ - [gs_echo.PagedExpandRequest], - Union[ - gs_echo.PagedExpandResponse, - Awaitable[gs_echo.PagedExpandResponse] - ]]: - raise NotImplementedError() - - @property - def paged_expand_legacy(self) -> Callable[ - [gs_echo.PagedExpandLegacyRequest], - Union[ - gs_echo.PagedExpandResponse, - Awaitable[gs_echo.PagedExpandResponse] - ]]: - raise NotImplementedError() - - @property - def paged_expand_legacy_mapped(self) -> Callable[ - [gs_echo.PagedExpandRequest], - Union[ - gs_echo.PagedExpandLegacyMappedResponse, - Awaitable[gs_echo.PagedExpandLegacyMappedResponse] - ]]: - raise NotImplementedError() - - @property - def wait(self) -> Callable[ - [gs_echo.WaitRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def block(self) -> Callable[ - [gs_echo.BlockRequest], - Union[ - gs_echo.BlockResponse, - Awaitable[gs_echo.BlockResponse] - ]]: - 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__ = ( - 'EchoTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py deleted file mode 100644 index f74aa619c4f6..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc.py +++ /dev/null @@ -1,831 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.showcase_v1beta1.types import echo as gs_echo -from .base import EchoTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EchoGrpcTransport(EchoTransport): - """gRPC backend transport for Echo. - - This service is used showcase the four main types of rpcs - - unary, server side streaming, client side streaming, and - bidirectional streaming. This service also exposes methods that - explicitly implement server delay, and paginated calls. Set the - 'showcase-trailer' metadata key on any method to have the values - echoed in the response trailers. Set the 'x-goog-request-params' - metadata key on any method to have the values echoed in the - response headers. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'localhost:7469', - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'localhost:7469', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def echo(self) -> Callable[ - [gs_echo.EchoRequest], - gs_echo.EchoResponse]: - r"""Return a callable for the echo method over gRPC. - - This method simply echoes the request. This method - showcases unary RPCs. - - Returns: - Callable[[~.EchoRequest], - ~.EchoResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'echo' not in self._stubs: - self._stubs['echo'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/Echo', - request_serializer=gs_echo.EchoRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['echo'] - - @property - def echo_error_details(self) -> Callable[ - [gs_echo.EchoErrorDetailsRequest], - gs_echo.EchoErrorDetailsResponse]: - r"""Return a callable for the echo error details method over gRPC. - - This method returns error details in a repeated - "google.protobuf.Any" field. This method showcases handling - errors thus encoded, particularly over REST transport. Note that - GAPICs only allow the type "google.protobuf.Any" for field paths - ending in "error.details", and, at run-time, the actual types - for these fields must be one of the types in - google/rpc/error_details.proto. - - Returns: - Callable[[~.EchoErrorDetailsRequest], - ~.EchoErrorDetailsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'echo_error_details' not in self._stubs: - self._stubs['echo_error_details'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/EchoErrorDetails', - request_serializer=gs_echo.EchoErrorDetailsRequest.serialize, - response_deserializer=gs_echo.EchoErrorDetailsResponse.deserialize, - ) - return self._stubs['echo_error_details'] - - @property - def expand(self) -> Callable[ - [gs_echo.ExpandRequest], - gs_echo.EchoResponse]: - r"""Return a callable for the expand method over gRPC. - - This method splits the given content into words and - will pass each word back through the stream. This method - showcases server-side streaming RPCs. - - Returns: - Callable[[~.ExpandRequest], - ~.EchoResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'expand' not in self._stubs: - self._stubs['expand'] = self._logged_channel.unary_stream( - '/google.showcase.v1beta1.Echo/Expand', - request_serializer=gs_echo.ExpandRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['expand'] - - @property - def collect(self) -> Callable[ - [gs_echo.EchoRequest], - gs_echo.EchoResponse]: - r"""Return a callable for the collect method over gRPC. - - This method will collect the words given to it. When - the stream is closed by the client, this method will - return the a concatenation of the strings passed to it. - This method showcases client-side streaming RPCs. - - Returns: - Callable[[~.EchoRequest], - ~.EchoResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect' not in self._stubs: - self._stubs['collect'] = self._logged_channel.stream_unary( - '/google.showcase.v1beta1.Echo/Collect', - request_serializer=gs_echo.EchoRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['collect'] - - @property - def chat(self) -> Callable[ - [gs_echo.EchoRequest], - gs_echo.EchoResponse]: - r"""Return a callable for the chat method over gRPC. - - This method, upon receiving a request on the stream, - will pass the same content back on the stream. This - method showcases bidirectional streaming RPCs. - - Returns: - Callable[[~.EchoRequest], - ~.EchoResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'chat' not in self._stubs: - self._stubs['chat'] = self._logged_channel.stream_stream( - '/google.showcase.v1beta1.Echo/Chat', - request_serializer=gs_echo.EchoRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['chat'] - - @property - def paged_expand(self) -> Callable[ - [gs_echo.PagedExpandRequest], - gs_echo.PagedExpandResponse]: - r"""Return a callable for the paged expand method over gRPC. - - This is similar to the Expand method but instead of - returning a stream of expanded words, this method - returns a paged list of expanded words. - - Returns: - Callable[[~.PagedExpandRequest], - ~.PagedExpandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'paged_expand' not in self._stubs: - self._stubs['paged_expand'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/PagedExpand', - request_serializer=gs_echo.PagedExpandRequest.serialize, - response_deserializer=gs_echo.PagedExpandResponse.deserialize, - ) - return self._stubs['paged_expand'] - - @property - def paged_expand_legacy(self) -> Callable[ - [gs_echo.PagedExpandLegacyRequest], - gs_echo.PagedExpandResponse]: - r"""Return a callable for the paged expand legacy method over gRPC. - - This is similar to the PagedExpand except that it uses - max_results instead of page_size, as some legacy APIs still do. - New APIs should NOT use this pattern. - - Returns: - Callable[[~.PagedExpandLegacyRequest], - ~.PagedExpandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'paged_expand_legacy' not in self._stubs: - self._stubs['paged_expand_legacy'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/PagedExpandLegacy', - request_serializer=gs_echo.PagedExpandLegacyRequest.serialize, - response_deserializer=gs_echo.PagedExpandResponse.deserialize, - ) - return self._stubs['paged_expand_legacy'] - - @property - def paged_expand_legacy_mapped(self) -> Callable[ - [gs_echo.PagedExpandRequest], - gs_echo.PagedExpandLegacyMappedResponse]: - r"""Return a callable for the paged expand legacy mapped method over gRPC. - - This method returns a map containing lists of words that appear - in the input, keyed by their initial character. The only words - returned are the ones included in the current page, as - determined by page_token and page_size, which both refer to the - word indices in the input. This paging result consisting of a - map of lists is a pattern used by some legacy APIs. New APIs - should NOT use this pattern. - - Returns: - Callable[[~.PagedExpandRequest], - ~.PagedExpandLegacyMappedResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'paged_expand_legacy_mapped' not in self._stubs: - self._stubs['paged_expand_legacy_mapped'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/PagedExpandLegacyMapped', - request_serializer=gs_echo.PagedExpandRequest.serialize, - response_deserializer=gs_echo.PagedExpandLegacyMappedResponse.deserialize, - ) - return self._stubs['paged_expand_legacy_mapped'] - - @property - def wait(self) -> Callable[ - [gs_echo.WaitRequest], - operations_pb2.Operation]: - r"""Return a callable for the wait method over gRPC. - - This method will wait for the requested amount of - time and then return. This method showcases how a client - handles a request timeout. - - Returns: - Callable[[~.WaitRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'wait' not in self._stubs: - self._stubs['wait'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/Wait', - request_serializer=gs_echo.WaitRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['wait'] - - @property - def block(self) -> Callable[ - [gs_echo.BlockRequest], - gs_echo.BlockResponse]: - r"""Return a callable for the block method over gRPC. - - This method will block (wait) for the requested - amount of time and then return the response or error. - This method showcases how a client handles delays or - retries. - - Returns: - Callable[[~.BlockRequest], - ~.BlockResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'block' not in self._stubs: - self._stubs['block'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/Block', - request_serializer=gs_echo.BlockRequest.serialize, - response_deserializer=gs_echo.BlockResponse.deserialize, - ) - return self._stubs['block'] - - def close(self): - self._logged_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EchoGrpcTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py deleted file mode 100644 index a7bd21b9e0ab..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/grpc_asyncio.py +++ /dev/null @@ -1,972 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.showcase_v1beta1.types import echo as gs_echo -from .base import EchoTransport, DEFAULT_CLIENT_INFO -from .grpc import EchoGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EchoGrpcAsyncIOTransport(EchoTransport): - """gRPC AsyncIO backend transport for Echo. - - This service is used showcase the four main types of rpcs - - unary, server side streaming, client side streaming, and - bidirectional streaming. This service also exposes methods that - explicitly implement server delay, and paginated calls. Set the - 'showcase-trailer' metadata key on any method to have the values - echoed in the response trailers. Set the 'x-goog-request-params' - metadata key on any method to have the values echoed in the - response headers. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'localhost:7469', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'localhost:7469', - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def echo(self) -> Callable[ - [gs_echo.EchoRequest], - Awaitable[gs_echo.EchoResponse]]: - r"""Return a callable for the echo method over gRPC. - - This method simply echoes the request. This method - showcases unary RPCs. - - Returns: - Callable[[~.EchoRequest], - Awaitable[~.EchoResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'echo' not in self._stubs: - self._stubs['echo'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/Echo', - request_serializer=gs_echo.EchoRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['echo'] - - @property - def echo_error_details(self) -> Callable[ - [gs_echo.EchoErrorDetailsRequest], - Awaitable[gs_echo.EchoErrorDetailsResponse]]: - r"""Return a callable for the echo error details method over gRPC. - - This method returns error details in a repeated - "google.protobuf.Any" field. This method showcases handling - errors thus encoded, particularly over REST transport. Note that - GAPICs only allow the type "google.protobuf.Any" for field paths - ending in "error.details", and, at run-time, the actual types - for these fields must be one of the types in - google/rpc/error_details.proto. - - Returns: - Callable[[~.EchoErrorDetailsRequest], - Awaitable[~.EchoErrorDetailsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'echo_error_details' not in self._stubs: - self._stubs['echo_error_details'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/EchoErrorDetails', - request_serializer=gs_echo.EchoErrorDetailsRequest.serialize, - response_deserializer=gs_echo.EchoErrorDetailsResponse.deserialize, - ) - return self._stubs['echo_error_details'] - - @property - def expand(self) -> Callable[ - [gs_echo.ExpandRequest], - Awaitable[gs_echo.EchoResponse]]: - r"""Return a callable for the expand method over gRPC. - - This method splits the given content into words and - will pass each word back through the stream. This method - showcases server-side streaming RPCs. - - Returns: - Callable[[~.ExpandRequest], - Awaitable[~.EchoResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'expand' not in self._stubs: - self._stubs['expand'] = self._logged_channel.unary_stream( - '/google.showcase.v1beta1.Echo/Expand', - request_serializer=gs_echo.ExpandRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['expand'] - - @property - def collect(self) -> Callable[ - [gs_echo.EchoRequest], - Awaitable[gs_echo.EchoResponse]]: - r"""Return a callable for the collect method over gRPC. - - This method will collect the words given to it. When - the stream is closed by the client, this method will - return the a concatenation of the strings passed to it. - This method showcases client-side streaming RPCs. - - Returns: - Callable[[~.EchoRequest], - Awaitable[~.EchoResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect' not in self._stubs: - self._stubs['collect'] = self._logged_channel.stream_unary( - '/google.showcase.v1beta1.Echo/Collect', - request_serializer=gs_echo.EchoRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['collect'] - - @property - def chat(self) -> Callable[ - [gs_echo.EchoRequest], - Awaitable[gs_echo.EchoResponse]]: - r"""Return a callable for the chat method over gRPC. - - This method, upon receiving a request on the stream, - will pass the same content back on the stream. This - method showcases bidirectional streaming RPCs. - - Returns: - Callable[[~.EchoRequest], - Awaitable[~.EchoResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'chat' not in self._stubs: - self._stubs['chat'] = self._logged_channel.stream_stream( - '/google.showcase.v1beta1.Echo/Chat', - request_serializer=gs_echo.EchoRequest.serialize, - response_deserializer=gs_echo.EchoResponse.deserialize, - ) - return self._stubs['chat'] - - @property - def paged_expand(self) -> Callable[ - [gs_echo.PagedExpandRequest], - Awaitable[gs_echo.PagedExpandResponse]]: - r"""Return a callable for the paged expand method over gRPC. - - This is similar to the Expand method but instead of - returning a stream of expanded words, this method - returns a paged list of expanded words. - - Returns: - Callable[[~.PagedExpandRequest], - Awaitable[~.PagedExpandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'paged_expand' not in self._stubs: - self._stubs['paged_expand'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/PagedExpand', - request_serializer=gs_echo.PagedExpandRequest.serialize, - response_deserializer=gs_echo.PagedExpandResponse.deserialize, - ) - return self._stubs['paged_expand'] - - @property - def paged_expand_legacy(self) -> Callable[ - [gs_echo.PagedExpandLegacyRequest], - Awaitable[gs_echo.PagedExpandResponse]]: - r"""Return a callable for the paged expand legacy method over gRPC. - - This is similar to the PagedExpand except that it uses - max_results instead of page_size, as some legacy APIs still do. - New APIs should NOT use this pattern. - - Returns: - Callable[[~.PagedExpandLegacyRequest], - Awaitable[~.PagedExpandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'paged_expand_legacy' not in self._stubs: - self._stubs['paged_expand_legacy'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/PagedExpandLegacy', - request_serializer=gs_echo.PagedExpandLegacyRequest.serialize, - response_deserializer=gs_echo.PagedExpandResponse.deserialize, - ) - return self._stubs['paged_expand_legacy'] - - @property - def paged_expand_legacy_mapped(self) -> Callable[ - [gs_echo.PagedExpandRequest], - Awaitable[gs_echo.PagedExpandLegacyMappedResponse]]: - r"""Return a callable for the paged expand legacy mapped method over gRPC. - - This method returns a map containing lists of words that appear - in the input, keyed by their initial character. The only words - returned are the ones included in the current page, as - determined by page_token and page_size, which both refer to the - word indices in the input. This paging result consisting of a - map of lists is a pattern used by some legacy APIs. New APIs - should NOT use this pattern. - - Returns: - Callable[[~.PagedExpandRequest], - Awaitable[~.PagedExpandLegacyMappedResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'paged_expand_legacy_mapped' not in self._stubs: - self._stubs['paged_expand_legacy_mapped'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/PagedExpandLegacyMapped', - request_serializer=gs_echo.PagedExpandRequest.serialize, - response_deserializer=gs_echo.PagedExpandLegacyMappedResponse.deserialize, - ) - return self._stubs['paged_expand_legacy_mapped'] - - @property - def wait(self) -> Callable[ - [gs_echo.WaitRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the wait method over gRPC. - - This method will wait for the requested amount of - time and then return. This method showcases how a client - handles a request timeout. - - Returns: - Callable[[~.WaitRequest], - 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 'wait' not in self._stubs: - self._stubs['wait'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/Wait', - request_serializer=gs_echo.WaitRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['wait'] - - @property - def block(self) -> Callable[ - [gs_echo.BlockRequest], - Awaitable[gs_echo.BlockResponse]]: - r"""Return a callable for the block method over gRPC. - - This method will block (wait) for the requested - amount of time and then return the response or error. - This method showcases how a client handles delays or - retries. - - Returns: - Callable[[~.BlockRequest], - Awaitable[~.BlockResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'block' not in self._stubs: - self._stubs['block'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Echo/Block', - request_serializer=gs_echo.BlockRequest.serialize, - response_deserializer=gs_echo.BlockResponse.deserialize, - ) - return self._stubs['block'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.echo: self._wrap_method( - self.echo, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.echo_error_details: self._wrap_method( - self.echo_error_details, - default_timeout=None, - client_info=client_info, - ), - self.expand: self._wrap_method( - self.expand, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.collect: self._wrap_method( - self.collect, - default_timeout=None, - client_info=client_info, - ), - self.chat: self._wrap_method( - self.chat, - default_timeout=None, - client_info=client_info, - ), - self.paged_expand: self._wrap_method( - self.paged_expand, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.paged_expand_legacy: self._wrap_method( - self.paged_expand_legacy, - default_timeout=None, - client_info=client_info, - ), - self.paged_expand_legacy_mapped: self._wrap_method( - self.paged_expand_legacy_mapped, - default_timeout=None, - client_info=client_info, - ), - self.wait: self._wrap_method( - self.wait, - default_timeout=None, - client_info=client_info, - ), - self.block: self._wrap_method( - self.block, - 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_location: self._wrap_method( - self.get_location, - 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.get_iam_policy: self._wrap_method( - self.get_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.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_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.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'EchoGrpcAsyncIOTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py deleted file mode 100644 index ade0c516ae2f..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest.py +++ /dev/null @@ -1,2975 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # 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.showcase_v1beta1 import _compat as rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -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.showcase_v1beta1.types import echo as gs_echo -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseEchoRestTransport -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 - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class EchoRestInterceptor: - """Interceptor for Echo. - - 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 EchoRestTransport. - - .. code-block:: python - class MyCustomEchoInterceptor(EchoRestInterceptor): - def pre_block(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_block(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_echo(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_echo(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_echo_error_details(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_echo_error_details(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_expand(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_expand(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_paged_expand(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_paged_expand(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_paged_expand_legacy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_paged_expand_legacy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_paged_expand_legacy_mapped(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_paged_expand_legacy_mapped(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_wait(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_wait(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EchoRestTransport(interceptor=MyCustomEchoInterceptor()) - client = EchoClient(transport=transport) - - - """ - def pre_block(self, request: gs_echo.BlockRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.BlockRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for block - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_block(self, response: gs_echo.BlockResponse) -> gs_echo.BlockResponse: - """Post-rpc interceptor for block - - DEPRECATED. Please use the `post_block_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_block` interceptor runs - before the `post_block_with_metadata` interceptor. - """ - return response - - def post_block_with_metadata(self, response: gs_echo.BlockResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.BlockResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for block - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_block_with_metadata` - interceptor in new development instead of the `post_block` interceptor. - When both interceptors are used, this `post_block_with_metadata` interceptor runs after the - `post_block` interceptor. The (possibly modified) response returned by - `post_block` will be passed to - `post_block_with_metadata`. - """ - return response, metadata - - def pre_echo(self, request: gs_echo.EchoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for echo - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_echo(self, response: gs_echo.EchoResponse) -> gs_echo.EchoResponse: - """Post-rpc interceptor for echo - - DEPRECATED. Please use the `post_echo_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_echo` interceptor runs - before the `post_echo_with_metadata` interceptor. - """ - return response - - def post_echo_with_metadata(self, response: gs_echo.EchoResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for echo - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_echo_with_metadata` - interceptor in new development instead of the `post_echo` interceptor. - When both interceptors are used, this `post_echo_with_metadata` interceptor runs after the - `post_echo` interceptor. The (possibly modified) response returned by - `post_echo` will be passed to - `post_echo_with_metadata`. - """ - return response, metadata - - def pre_echo_error_details(self, request: gs_echo.EchoErrorDetailsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoErrorDetailsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for echo_error_details - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_echo_error_details(self, response: gs_echo.EchoErrorDetailsResponse) -> gs_echo.EchoErrorDetailsResponse: - """Post-rpc interceptor for echo_error_details - - DEPRECATED. Please use the `post_echo_error_details_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_echo_error_details` interceptor runs - before the `post_echo_error_details_with_metadata` interceptor. - """ - return response - - def post_echo_error_details_with_metadata(self, response: gs_echo.EchoErrorDetailsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.EchoErrorDetailsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for echo_error_details - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_echo_error_details_with_metadata` - interceptor in new development instead of the `post_echo_error_details` interceptor. - When both interceptors are used, this `post_echo_error_details_with_metadata` interceptor runs after the - `post_echo_error_details` interceptor. The (possibly modified) response returned by - `post_echo_error_details` will be passed to - `post_echo_error_details_with_metadata`. - """ - return response, metadata - - def pre_expand(self, request: gs_echo.ExpandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.ExpandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for expand - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_expand(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for expand - - DEPRECATED. Please use the `post_expand_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_expand` interceptor runs - before the `post_expand_with_metadata` interceptor. - """ - return response - - def post_expand_with_metadata(self, response: rest_streaming.ResponseIterator, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for expand - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_expand_with_metadata` - interceptor in new development instead of the `post_expand` interceptor. - When both interceptors are used, this `post_expand_with_metadata` interceptor runs after the - `post_expand` interceptor. The (possibly modified) response returned by - `post_expand` will be passed to - `post_expand_with_metadata`. - """ - return response, metadata - - def pre_paged_expand(self, request: gs_echo.PagedExpandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for paged_expand - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_paged_expand(self, response: gs_echo.PagedExpandResponse) -> gs_echo.PagedExpandResponse: - """Post-rpc interceptor for paged_expand - - DEPRECATED. Please use the `post_paged_expand_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_paged_expand` interceptor runs - before the `post_paged_expand_with_metadata` interceptor. - """ - return response - - def post_paged_expand_with_metadata(self, response: gs_echo.PagedExpandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for paged_expand - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_paged_expand_with_metadata` - interceptor in new development instead of the `post_paged_expand` interceptor. - When both interceptors are used, this `post_paged_expand_with_metadata` interceptor runs after the - `post_paged_expand` interceptor. The (possibly modified) response returned by - `post_paged_expand` will be passed to - `post_paged_expand_with_metadata`. - """ - return response, metadata - - def pre_paged_expand_legacy(self, request: gs_echo.PagedExpandLegacyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandLegacyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for paged_expand_legacy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_paged_expand_legacy(self, response: gs_echo.PagedExpandResponse) -> gs_echo.PagedExpandResponse: - """Post-rpc interceptor for paged_expand_legacy - - DEPRECATED. Please use the `post_paged_expand_legacy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_paged_expand_legacy` interceptor runs - before the `post_paged_expand_legacy_with_metadata` interceptor. - """ - return response - - def post_paged_expand_legacy_with_metadata(self, response: gs_echo.PagedExpandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for paged_expand_legacy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_paged_expand_legacy_with_metadata` - interceptor in new development instead of the `post_paged_expand_legacy` interceptor. - When both interceptors are used, this `post_paged_expand_legacy_with_metadata` interceptor runs after the - `post_paged_expand_legacy` interceptor. The (possibly modified) response returned by - `post_paged_expand_legacy` will be passed to - `post_paged_expand_legacy_with_metadata`. - """ - return response, metadata - - def pre_paged_expand_legacy_mapped(self, request: gs_echo.PagedExpandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for paged_expand_legacy_mapped - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_paged_expand_legacy_mapped(self, response: gs_echo.PagedExpandLegacyMappedResponse) -> gs_echo.PagedExpandLegacyMappedResponse: - """Post-rpc interceptor for paged_expand_legacy_mapped - - DEPRECATED. Please use the `post_paged_expand_legacy_mapped_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_paged_expand_legacy_mapped` interceptor runs - before the `post_paged_expand_legacy_mapped_with_metadata` interceptor. - """ - return response - - def post_paged_expand_legacy_mapped_with_metadata(self, response: gs_echo.PagedExpandLegacyMappedResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.PagedExpandLegacyMappedResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for paged_expand_legacy_mapped - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_paged_expand_legacy_mapped_with_metadata` - interceptor in new development instead of the `post_paged_expand_legacy_mapped` interceptor. - When both interceptors are used, this `post_paged_expand_legacy_mapped_with_metadata` interceptor runs after the - `post_paged_expand_legacy_mapped` interceptor. The (possibly modified) response returned by - `post_paged_expand_legacy_mapped` will be passed to - `post_paged_expand_legacy_mapped_with_metadata`. - """ - return response, metadata - - def pre_wait(self, request: gs_echo.WaitRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gs_echo.WaitRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for wait - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo server. - """ - return request, metadata - - def post_wait(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for wait - - DEPRECATED. Please use the `post_wait_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Echo server but before - it is returned to user code. This `post_wait` interceptor runs - before the `post_wait_with_metadata` interceptor. - """ - return response - - def post_wait_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for wait - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Echo server but before it is returned to user code. - - We recommend only using this `post_wait_with_metadata` - interceptor in new development instead of the `post_wait` interceptor. - When both interceptors are used, this `post_wait_with_metadata` interceptor runs after the - `post_wait` interceptor. The (possibly modified) response returned by - `post_wait` will be passed to - `post_wait_with_metadata`. - """ - return response, metadata - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Echo 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 Echo server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EchoRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EchoRestInterceptor - - -class EchoRestTransport(_BaseEchoRestTransport): - """REST backend synchronous transport for Echo. - - This service is used showcase the four main types of rpcs - - unary, server side streaming, client side streaming, and - bidirectional streaming. This service also exposes methods that - explicitly implement server delay, and paginated calls. Set the - 'showcase-trailer' metadata key on any method to have the values - echoed in the response trailers. Set the 'x-goog-request-params' - metadata key on any method to have the values echoed in the - response headers. - - This 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 = 'localhost:7469', - 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[EchoRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[EchoRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - """ - # 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 EchoRestInterceptor() - 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.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta1/operations', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=operations/**}', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta1/{name=operations/**}', - }, - ], - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta1/{name=operations/**}:cancel', - }, - ], - } - - 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="v1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _Block(_BaseEchoRestTransport._BaseBlock, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.Block") - - @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: gs_echo.BlockRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.BlockResponse: - r"""Call the block method over HTTP. - - Args: - request (~.gs_echo.BlockRequest): - The request object. The request for Block method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.BlockResponse: - The response for Block method. - """ - - http_options = _BaseEchoRestTransport._BaseBlock._get_http_options() - request, metadata = self._interceptor.pre_block(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseBlock, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.Block", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Block", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._Block._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 = gs_echo.BlockResponse() - pb_resp = gs_echo.BlockResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_block(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_block_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gs_echo.BlockResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.block", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Block", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _Chat(_BaseEchoRestTransport._BaseChat, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.Chat") - - def __call__(self, - request: gs_echo.EchoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method Chat is not available over REST transport" - ) - class _Collect(_BaseEchoRestTransport._BaseCollect, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.Collect") - - def __call__(self, - request: gs_echo.EchoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.EchoResponse: - raise NotImplementedError( - "Method Collect is not available over REST transport" - ) - class _Echo(_BaseEchoRestTransport._BaseEcho, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.Echo") - - @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: gs_echo.EchoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.EchoResponse: - r"""Call the echo method over HTTP. - - Args: - request (~.gs_echo.EchoRequest): - The request object. The request message used for the - Echo, Collect and Chat methods. If - content or opt are set in this message - then the request will succeed. If status - is set in this message then the status - will be returned as an error. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.EchoResponse: - The response message for the Echo - methods. - - """ - - http_options = _BaseEchoRestTransport._BaseEcho._get_http_options() - request, metadata = self._interceptor.pre_echo(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseEcho, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.Echo", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Echo", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._Echo._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 = gs_echo.EchoResponse() - pb_resp = gs_echo.EchoResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_echo(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_echo_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gs_echo.EchoResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.echo", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Echo", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _EchoErrorDetails(_BaseEchoRestTransport._BaseEchoErrorDetails, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.EchoErrorDetails") - - @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: gs_echo.EchoErrorDetailsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.EchoErrorDetailsResponse: - r"""Call the echo error details method over HTTP. - - Args: - request (~.gs_echo.EchoErrorDetailsRequest): - The request object. The request message used for the - EchoErrorDetails method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.EchoErrorDetailsResponse: - The response message used for the - EchoErrorDetails method. - - """ - - http_options = _BaseEchoRestTransport._BaseEchoErrorDetails._get_http_options() - request, metadata = self._interceptor.pre_echo_error_details(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseEchoErrorDetails, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.EchoErrorDetails", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "EchoErrorDetails", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._EchoErrorDetails._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 = gs_echo.EchoErrorDetailsResponse() - pb_resp = gs_echo.EchoErrorDetailsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_echo_error_details(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_echo_error_details_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gs_echo.EchoErrorDetailsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.echo_error_details", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "EchoErrorDetails", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _Expand(_BaseEchoRestTransport._BaseExpand, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.Expand") - - @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, - stream=True, - ) - return response - - def __call__(self, - request: gs_echo.ExpandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the expand method over HTTP. - - Args: - request (~.gs_echo.ExpandRequest): - The request object. The request message for the Expand - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.EchoResponse: - The response message for the Echo - methods. - - """ - - http_options = _BaseEchoRestTransport._BaseExpand._get_http_options() - request, metadata = self._interceptor.pre_expand(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseExpand, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.Expand", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Expand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._Expand._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 = rest_streaming.ResponseIterator(response, gs_echo.EchoResponse) - - resp = self._interceptor.post_expand(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_expand_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - http_response = { - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.expand", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Expand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _PagedExpand(_BaseEchoRestTransport._BasePagedExpand, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.PagedExpand") - - @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: gs_echo.PagedExpandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.PagedExpandResponse: - r"""Call the paged expand method over HTTP. - - Args: - request (~.gs_echo.PagedExpandRequest): - The request object. The request for the PagedExpand - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.PagedExpandResponse: - The response for the PagedExpand - method. - - """ - - http_options = _BaseEchoRestTransport._BasePagedExpand._get_http_options() - request, metadata = self._interceptor.pre_paged_expand(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BasePagedExpand, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.PagedExpand", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "PagedExpand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._PagedExpand._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 = gs_echo.PagedExpandResponse() - pb_resp = gs_echo.PagedExpandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_paged_expand(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_paged_expand_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gs_echo.PagedExpandResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.paged_expand", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "PagedExpand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _PagedExpandLegacy(_BaseEchoRestTransport._BasePagedExpandLegacy, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.PagedExpandLegacy") - - @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: gs_echo.PagedExpandLegacyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.PagedExpandResponse: - r"""Call the paged expand legacy method over HTTP. - - Args: - request (~.gs_echo.PagedExpandLegacyRequest): - The request object. The request for the PagedExpandLegacy - method. This is a pattern used by some - legacy APIs. New APIs should NOT use - this pattern, but rather something like - PagedExpandRequest which conforms to - aip.dev/158. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.PagedExpandResponse: - The response for the PagedExpand - method. - - """ - - http_options = _BaseEchoRestTransport._BasePagedExpandLegacy._get_http_options() - request, metadata = self._interceptor.pre_paged_expand_legacy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BasePagedExpandLegacy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.PagedExpandLegacy", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "PagedExpandLegacy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._PagedExpandLegacy._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 = gs_echo.PagedExpandResponse() - pb_resp = gs_echo.PagedExpandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_paged_expand_legacy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_paged_expand_legacy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gs_echo.PagedExpandResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.paged_expand_legacy", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "PagedExpandLegacy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _PagedExpandLegacyMapped(_BaseEchoRestTransport._BasePagedExpandLegacyMapped, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.PagedExpandLegacyMapped") - - @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: gs_echo.PagedExpandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gs_echo.PagedExpandLegacyMappedResponse: - r"""Call the paged expand legacy - mapped method over HTTP. - - Args: - request (~.gs_echo.PagedExpandRequest): - The request object. The request for the PagedExpand - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gs_echo.PagedExpandLegacyMappedResponse: - - """ - - http_options = _BaseEchoRestTransport._BasePagedExpandLegacyMapped._get_http_options() - request, metadata = self._interceptor.pre_paged_expand_legacy_mapped(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BasePagedExpandLegacyMapped, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.PagedExpandLegacyMapped", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "PagedExpandLegacyMapped", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._PagedExpandLegacyMapped._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 = gs_echo.PagedExpandLegacyMappedResponse() - pb_resp = gs_echo.PagedExpandLegacyMappedResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_paged_expand_legacy_mapped(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_paged_expand_legacy_mapped_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gs_echo.PagedExpandLegacyMappedResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.paged_expand_legacy_mapped", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "PagedExpandLegacyMapped", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _Wait(_BaseEchoRestTransport._BaseWait, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.Wait") - - @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: gs_echo.WaitRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the wait method over HTTP. - - Args: - request (~.gs_echo.WaitRequest): - The request object. The request for Wait method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEchoRestTransport._BaseWait._get_http_options() - request, metadata = self._interceptor.pre_wait(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseWait, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.Wait", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Wait", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._Wait._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_wait(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_wait_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoClient.wait", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "Wait", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def block(self) -> Callable[ - [gs_echo.BlockRequest], - gs_echo.BlockResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Block(self._session, self._host, self._interceptor) # type: ignore - - @property - def chat(self) -> Callable[ - [gs_echo.EchoRequest], - gs_echo.EchoResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Chat(self._session, self._host, self._interceptor) # type: ignore - - @property - def collect(self) -> Callable[ - [gs_echo.EchoRequest], - gs_echo.EchoResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Collect(self._session, self._host, self._interceptor) # type: ignore - - @property - def echo(self) -> Callable[ - [gs_echo.EchoRequest], - gs_echo.EchoResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Echo(self._session, self._host, self._interceptor) # type: ignore - - @property - def echo_error_details(self) -> Callable[ - [gs_echo.EchoErrorDetailsRequest], - gs_echo.EchoErrorDetailsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._EchoErrorDetails(self._session, self._host, self._interceptor) # type: ignore - - @property - def expand(self) -> Callable[ - [gs_echo.ExpandRequest], - gs_echo.EchoResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Expand(self._session, self._host, self._interceptor) # type: ignore - - @property - def paged_expand(self) -> Callable[ - [gs_echo.PagedExpandRequest], - gs_echo.PagedExpandResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._PagedExpand(self._session, self._host, self._interceptor) # type: ignore - - @property - def paged_expand_legacy(self) -> Callable[ - [gs_echo.PagedExpandLegacyRequest], - gs_echo.PagedExpandResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._PagedExpandLegacy(self._session, self._host, self._interceptor) # type: ignore - - @property - def paged_expand_legacy_mapped(self) -> Callable[ - [gs_echo.PagedExpandRequest], - gs_echo.PagedExpandLegacyMappedResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._PagedExpandLegacyMapped(self._session, self._host, self._interceptor) # type: ignore - - @property - def wait(self) -> Callable[ - [gs_echo.WaitRequest], - 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._Wait(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseEchoRestTransport._BaseListLocations, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseEchoRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseListLocations, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.ListLocations", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "ListLocations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.ListLocations", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "ListLocations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseEchoRestTransport._BaseGetLocation, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseEchoRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseGetLocation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.GetLocation", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "GetLocation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.GetLocation", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "GetLocation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseEchoRestTransport._BaseSetIamPolicy, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseEchoRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseSetIamPolicy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.SetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "SetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseEchoRestTransport._BaseGetIamPolicy, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseEchoRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseGetIamPolicy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.GetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "GetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseEchoRestTransport._BaseTestIamPermissions, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseEchoRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseTestIamPermissions, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.TestIamPermissions", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "TestIamPermissions", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseEchoRestTransport._BaseListOperations, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseEchoRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseListOperations, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.ListOperations", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.ListOperations", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseEchoRestTransport._BaseGetOperation, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseEchoRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseGetOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.GetOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.EchoAsyncClient.GetOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseEchoRestTransport._BaseDeleteOperation, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseEchoRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseDeleteOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.DeleteOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._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 cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseEchoRestTransport._BaseCancelOperation, EchoRestStub): - def __hash__(self): - return hash("EchoRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseEchoRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseEchoRestTransport._BaseCancelOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.EchoClient.CancelOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Echo", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EchoRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EchoRestTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py deleted file mode 100644 index 7c79f74ec328..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/echo/transports/rest_base.py +++ /dev/null @@ -1,412 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 EchoTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.showcase_v1beta1.types import echo as gs_echo -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseEchoRestTransport(EchoTransport): - """Base REST backend transport for Echo. - - 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 = 'localhost:7469', - 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: 'localhost:7469'). - 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 _BaseBlock: - 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': '/v1beta1/echo:block', - 'body': '*', - }, - ] - return http_options - - class _BaseChat: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - class _BaseCollect: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - class _BaseEcho: - 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': '/v1beta1/echo:echo', - 'body': '*', - }, - ] - return http_options - - class _BaseEchoErrorDetails: - 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': '/v1beta1/echo:error-details', - 'body': '*', - }, - ] - return http_options - - class _BaseExpand: - 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': '/v1beta1/echo:expand', - 'body': '*', - }, - ] - return http_options - - class _BasePagedExpand: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/echo:pagedExpand', - 'body': '*', - }, - ] - return http_options - - class _BasePagedExpandLegacy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/echo:pagedExpandLegacy', - 'body': '*', - }, - ] - return http_options - - class _BasePagedExpandLegacyMapped: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/echo:pagedExpandLegacyMapped', - 'body': '*', - }, - ] - return http_options - - class _BaseWait: - 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': '/v1beta1/echo:wait', - 'body': '*', - }, - ] - return http_options - - 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': '/v1beta1/{name=projects/*}/locations', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=projects/*/locations/*}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=sequences/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=rooms/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=sequences/*}:getIamPolicy', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=sequences/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - pass - - 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': '/v1beta1/operations', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}:cancel', - }, - ] - return http_options - - pass - - -__all__=( - '_BaseEchoRestTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py deleted file mode 100644 index 9b1629e41d24..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 IdentityClient -from .async_client import IdentityAsyncClient - -__all__ = ( - 'IdentityClient', - 'IdentityAsyncClient', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py deleted file mode 100644 index 17a0c6e830dc..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/async_client.py +++ /dev/null @@ -1,1441 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import uuid - -from google.showcase_v1beta1 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 -import google.protobuf - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.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.showcase_v1beta1.services.identity import pagers -from google.showcase_v1beta1.types import identity -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import IdentityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import IdentityGrpcAsyncIOTransport -from .client import IdentityClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class IdentityAsyncClient: - """A simple identity service.""" - - _client: IdentityClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = IdentityClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = IdentityClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = IdentityClient._DEFAULT_UNIVERSE - - user_path = staticmethod(IdentityClient.user_path) - parse_user_path = staticmethod(IdentityClient.parse_user_path) - common_billing_account_path = staticmethod(IdentityClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(IdentityClient.parse_common_billing_account_path) - common_folder_path = staticmethod(IdentityClient.common_folder_path) - parse_common_folder_path = staticmethod(IdentityClient.parse_common_folder_path) - common_organization_path = staticmethod(IdentityClient.common_organization_path) - parse_common_organization_path = staticmethod(IdentityClient.parse_common_organization_path) - common_project_path = staticmethod(IdentityClient.common_project_path) - parse_common_project_path = staticmethod(IdentityClient.parse_common_project_path) - common_location_path = staticmethod(IdentityClient.common_location_path) - parse_common_location_path = staticmethod(IdentityClient.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: - IdentityAsyncClient: The constructed client. - """ - sa_info_func = ( - IdentityClient.from_service_account_info.__func__ # type: ignore - ) - return sa_info_func(IdentityAsyncClient, info, *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: - IdentityAsyncClient: The constructed client. - """ - sa_file_func = ( - IdentityClient.from_service_account_file.__func__ # type: ignore - ) - return sa_file_func(IdentityAsyncClient, filename, *args, **kwargs) - - 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 IdentityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> IdentityTransport: - """Returns the transport used by the client instance. - - Returns: - IdentityTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self) -> str: - """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 = IdentityClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IdentityTransport, Callable[..., IdentityTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the identity 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,IdentityTransport,Callable[..., IdentityTransport]]]): - 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 IdentityTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - 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 = IdentityClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.showcase_v1beta1.IdentityAsyncClient`.", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.showcase.v1beta1.Identity", - "credentialsType": None, - } - ) - - async def create_user(self, - request: Optional[Union[identity.CreateUserRequest, dict]] = None, - *, - display_name: Optional[str] = None, - email: Optional[str] = None, - age: Optional[int] = None, - nickname: Optional[str] = None, - enable_notifications: Optional[bool] = None, - height_feet: Optional[float] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> identity.User: - r"""Creates a user. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_create_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateUserRequest( - ) - - # Make the request - response = await client.create_user(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.CreateUserRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Identity\CreateUser - method. - display_name (:class:`str`): - The display_name of the user. - This corresponds to the ``user.display_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - email (:class:`str`): - The email address of the user. - This corresponds to the ``user.email`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - age (:class:`int`): - The age of the user in years. - This corresponds to the ``user.age`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - nickname (:class:`str`): - The nickname of the user. - - (-- aip.dev/not-precedent: An empty string is a valid - nickname. Ordinarily, proto3_optional should not be used - on a ``string`` field. --) - - This corresponds to the ``user.nickname`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - enable_notifications (:class:`bool`): - Enables the receiving of notifications. The default is - true if unset. - - (-- aip.dev/not-precedent: The default for the feature - is true. Ordinarily, the default for a ``bool`` field - should be false. --) - - This corresponds to the ``user.enable_notifications`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - height_feet (:class:`float`): - The height of the user in feet. - This corresponds to the ``user.height_feet`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.User: - A user. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [display_name, email, age, nickname, enable_notifications, height_feet] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.CreateUserRequest): - request = identity.CreateUserRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if display_name is not None: - request.user.display_name = display_name - if email is not None: - request.user.email = email - if age is not None: - request.user.age = age - if nickname is not None: - request.user.nickname = nickname - if enable_notifications is not None: - request.user.enable_notifications = enable_notifications - if height_feet is not None: - request.user.height_feet = height_feet - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user] - - # 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_user(self, - request: Optional[Union[identity.GetUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> identity.User: - r"""Retrieves the User with the given uri. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_get_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetUserRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.GetUserRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Identity\GetUser - method. - name (:class:`str`): - The resource name of the requested - user. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.User: - A user. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.GetUserRequest): - request = identity.GetUserRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_user] - - # Certain 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_user(self, - request: Optional[Union[identity.UpdateUserRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> identity.User: - r"""Updates a user. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_update_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateUserRequest( - ) - - # Make the request - response = await client.update_user(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.UpdateUserRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Identity\UpdateUser - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.User: - A user. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.UpdateUserRequest): - request = identity.UpdateUserRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user.name", request.user.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_user(self, - request: Optional[Union[identity.DeleteUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a user, their profile, and all of their - authored messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_delete_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteUserRequest( - name="name_value", - ) - - # Make the request - await client.delete_user(request=request) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.DeleteUserRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Identity\DeleteUser - method. - name (:class:`str`): - The resource name of the user to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.DeleteUserRequest): - request = identity.DeleteUserRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_user] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_users(self, - request: Optional[Union[identity.ListUsersRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListUsersAsyncPager: - r"""Lists all users. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_list_users(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListUsersRequest( - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.ListUsersRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Identity\ListUsers - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.identity.pagers.ListUsersAsyncPager: - The response message for the - google.showcase.v1beta1.Identity\ListUsers - method. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.ListUsersRequest): - request = identity.ListUsersRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_users] - - # 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.ListUsersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.DeleteOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.DeleteOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.CancelOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.CancelOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.SetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.GetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.TestIamPermissionsRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.GetLocationRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.GetLocationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.ListLocationsRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.ListLocationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "IdentityAsyncClient": - 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__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "IdentityAsyncClient", -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py deleted file mode 100644 index 84a36f09cb88..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/client.py +++ /dev/null @@ -1,1872 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import uuid -import warnings - -from google.showcase_v1beta1 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 -import google.protobuf - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.cloud.location import locations_pb2 # type: ignore -from google.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.showcase_v1beta1.services.identity import pagers -from google.showcase_v1beta1.types import identity -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import IdentityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import IdentityGrpcTransport -from .transports.grpc_asyncio import IdentityGrpcAsyncIOTransport -from .transports.rest import IdentityRestTransport - - -class IdentityClientMeta(type): - """Metaclass for the Identity 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[IdentityTransport]] - _transport_registry["grpc"] = IdentityGrpcTransport - _transport_registry["grpc_asyncio"] = IdentityGrpcAsyncIOTransport - _transport_registry["rest"] = IdentityRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[IdentityTransport]: - """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 IdentityClient(metaclass=IdentityClientMeta): - """A simple identity service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: - """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: - Optional[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) - if m is None: - # Could not parse api_endpoint; return as-is. - return 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 = "localhost:7469" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "localhost:7469" - _DEFAULT_UNIVERSE = "googleapis.com" - - @staticmethod - def _use_client_cert_effective(): - """Returns whether client certificate should be used for mTLS if the - google-auth version supports should_use_client_cert automatic mTLS enablement. - - Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. - - Returns: - bool: whether client certificate should be used for mTLS - Raises: - ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) - """ - # check if google-auth version supports should_use_client_cert for automatic mTLS enablement - if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER - return mtls.should_use_client_cert() - else: # pragma: NO COVER - # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - if use_client_cert_str not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" - " either `true` or `false`" - ) - return use_client_cert_str == "true" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - IdentityClient: 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: - IdentityClient: 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) -> IdentityTransport: - """Returns the transport used by the client instance. - - Returns: - IdentityTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def user_path(user: str,) -> str: - """Returns a fully-qualified user string.""" - return "users/{user}".format(user=user, ) - - @staticmethod - def parse_user_path(path: str) -> Dict[str,str]: - """Parses a user path into its component segments.""" - m = re.match(r"^users/(?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 = IdentityClient._use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = IdentityClient._use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert, use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: - """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 = IdentityClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = IdentityClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = IdentityClient._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 = IdentityClient._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 - - @staticmethod - def _setup_request_id(request, field_name: str, is_proto3_optional: bool): - """Populate a UUID4 field in the request if it is not already set. - - Args: - request (Union[google.protobuf.message.Message, dict]): The request object. - field_name (str): The name of the field to populate. - is_proto3_optional (bool): Whether the field is proto3 optional. - """ - if isinstance(request, dict): - if is_proto3_optional: - if field_name not in request: - request[field_name] = str(uuid.uuid4()) - elif not request.get(field_name): - request[field_name] = str(uuid.uuid4()) - return - - if is_proto3_optional: - try: - # Pure protobuf messages - if not request.HasField(field_name): - setattr(request, field_name, str(uuid.uuid4())) - except (AttributeError, ValueError): - # Proto-plus messages or other objects - if field_name not in request: - setattr(request, field_name, str(uuid.uuid4())) - else: - if not getattr(request, field_name): - setattr(request, field_name, str(uuid.uuid4())) - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self) -> str: - """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, IdentityTransport, Callable[..., IdentityTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the identity client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. 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,IdentityTransport,Callable[..., IdentityTransport]]]): - 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 IdentityTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - 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 = IdentityClient._read_environment_variables() - self._client_cert_source = IdentityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = IdentityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint: str = "" # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, IdentityTransport) - if transport_provided: - # transport is a IdentityTransport 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(IdentityTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - IdentityClient._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[IdentityTransport], Callable[..., IdentityTransport]] = ( - IdentityClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., IdentityTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.showcase_v1beta1.IdentityClient`.", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.showcase.v1beta1.Identity", - "credentialsType": None, - } - ) - - def create_user(self, - request: Optional[Union[identity.CreateUserRequest, dict]] = None, - *, - display_name: Optional[str] = None, - email: Optional[str] = None, - age: Optional[int] = None, - nickname: Optional[str] = None, - enable_notifications: Optional[bool] = None, - height_feet: Optional[float] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> identity.User: - r"""Creates a user. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_create_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateUserRequest( - ) - - # Make the request - response = client.create_user(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.CreateUserRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Identity\CreateUser - method. - display_name (str): - The display_name of the user. - This corresponds to the ``user.display_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - email (str): - The email address of the user. - This corresponds to the ``user.email`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - age (int): - The age of the user in years. - This corresponds to the ``user.age`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - nickname (str): - The nickname of the user. - - (-- aip.dev/not-precedent: An empty string is a valid - nickname. Ordinarily, proto3_optional should not be used - on a ``string`` field. --) - - This corresponds to the ``user.nickname`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - enable_notifications (bool): - Enables the receiving of notifications. The default is - true if unset. - - (-- aip.dev/not-precedent: The default for the feature - is true. Ordinarily, the default for a ``bool`` field - should be false. --) - - This corresponds to the ``user.enable_notifications`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - height_feet (float): - The height of the user in feet. - This corresponds to the ``user.height_feet`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.User: - A user. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [display_name, email, age, nickname, enable_notifications, height_feet] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.CreateUserRequest): - request = identity.CreateUserRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if display_name is not None: - request.user.display_name = display_name - if email is not None: - request.user.email = email - if age is not None: - request.user.age = age - if nickname is not None: - request.user.nickname = nickname - if enable_notifications is not None: - request.user.enable_notifications = enable_notifications - if height_feet is not None: - request.user.height_feet = height_feet - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_user] - - # 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_user(self, - request: Optional[Union[identity.GetUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> identity.User: - r"""Retrieves the User with the given uri. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_get_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetUserRequest( - name="name_value", - ) - - # Make the request - response = client.get_user(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.GetUserRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Identity\GetUser - method. - name (str): - The resource name of the requested - user. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.User: - A user. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.GetUserRequest): - request = identity.GetUserRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_user] - - # Certain 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_user(self, - request: Optional[Union[identity.UpdateUserRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> identity.User: - r"""Updates a user. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_update_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateUserRequest( - ) - - # Make the request - response = client.update_user(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.UpdateUserRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Identity\UpdateUser - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.User: - A user. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.UpdateUserRequest): - request = identity.UpdateUserRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_user] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user.name", request.user.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_user(self, - request: Optional[Union[identity.DeleteUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a user, their profile, and all of their - authored messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_delete_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteUserRequest( - name="name_value", - ) - - # Make the request - client.delete_user(request=request) - - Args: - request (Union[google.showcase_v1beta1.types.DeleteUserRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Identity\DeleteUser - method. - name (str): - The resource name of the user to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.DeleteUserRequest): - request = identity.DeleteUserRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_user] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_users(self, - request: Optional[Union[identity.ListUsersRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListUsersPager: - r"""Lists all users. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_list_users(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListUsersRequest( - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.ListUsersRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Identity\ListUsers - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.identity.pagers.ListUsersPager: - The response message for the - google.showcase.v1beta1.Identity\ListUsers - method. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, identity.ListUsersRequest): - request = identity.ListUsersRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_users] - - # 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.ListUsersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "IdentityClient": - 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_operation( - self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def delete_operation( - self, - request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.DeleteOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.DeleteOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.CancelOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.CancelOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.SetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.GetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def test_iam_permissions( - self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.TestIamPermissionsRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_location( - self, - request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.GetLocationRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.GetLocationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def list_locations( - self, - request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.ListLocationsRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.ListLocationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "IdentityClient", -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py deleted file mode 100644 index fc969a954c08..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1.types import identity - - -class ListUsersPager: - """A pager for iterating through ``list_users`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.ListUsersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``users`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsers`` requests and continue to iterate - through the ``users`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.ListUsersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., identity.ListUsersResponse], - request: identity.ListUsersRequest, - response: identity.ListUsersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.ListUsersRequest): - The initial request object. - response (google.showcase_v1beta1.types.ListUsersResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = identity.ListUsersRequest(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[identity.ListUsersResponse]: - 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[identity.User]: - for page in self.pages: - yield from page.users - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsersAsyncPager: - """A pager for iterating through ``list_users`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.ListUsersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``users`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsers`` requests and continue to iterate - through the ``users`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.ListUsersResponse` - attributes are available on the 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[identity.ListUsersResponse]], - request: identity.ListUsersRequest, - response: identity.ListUsersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.ListUsersRequest): - The initial request object. - response (google.showcase_v1beta1.types.ListUsersResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = identity.ListUsersRequest(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[identity.ListUsersResponse]: - 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[identity.User]: - async def async_generator(): - async for page in self.pages: - for response in page.users: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst deleted file mode 100644 index 180184c080a6..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/README.rst +++ /dev/null @@ -1,10 +0,0 @@ - -transport inheritance structure -_______________________________ - -``IdentityTransport`` is the ABC for all transports. - -- public child ``IdentityGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). -- public child ``IdentityGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). -- private child ``_BaseIdentityRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). -- public child ``IdentityRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py deleted file mode 100644 index c15bd7deb425..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 IdentityTransport -from .grpc import IdentityGrpcTransport -from .grpc_asyncio import IdentityGrpcAsyncIOTransport -from .rest import IdentityRestTransport -from .rest import IdentityRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[IdentityTransport]] -_transport_registry['grpc'] = IdentityGrpcTransport -_transport_registry['grpc_asyncio'] = IdentityGrpcAsyncIOTransport -_transport_registry['rest'] = IdentityRestTransport - -__all__ = ( - 'IdentityTransport', - 'IdentityGrpcTransport', - 'IdentityGrpcAsyncIOTransport', - 'IdentityRestTransport', - 'IdentityRestInterceptor', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py deleted file mode 100644 index 3d8c1973d646..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/base.py +++ /dev/null @@ -1,370 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -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.showcase_v1beta1.types import identity -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class IdentityTransport(abc.ABC): - """Abstract transport class for Identity.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'localhost:7469' - - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - """ - - # 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) - # 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 - - self._wrapped_methods: Dict[Callable, Callable] = {} - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_user: gapic_v1.method.wrap_method( - self.create_user, - default_timeout=None, - client_info=client_info, - ), - self.get_user: gapic_v1.method.wrap_method( - self.get_user, - default_retry=retries.Retry( - initial=0.2, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=5.0, - ), - default_timeout=5.0, - client_info=client_info, - ), - self.update_user: gapic_v1.method.wrap_method( - self.update_user, - default_timeout=None, - client_info=client_info, - ), - self.delete_user: gapic_v1.method.wrap_method( - self.delete_user, - default_timeout=None, - client_info=client_info, - ), - self.list_users: gapic_v1.method.wrap_method( - self.list_users, - default_retry=retries.Retry( - initial=0.2, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=5.0, - ), - default_timeout=5.0, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - 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.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_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.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_user(self) -> Callable[ - [identity.CreateUserRequest], - Union[ - identity.User, - Awaitable[identity.User] - ]]: - raise NotImplementedError() - - @property - def get_user(self) -> Callable[ - [identity.GetUserRequest], - Union[ - identity.User, - Awaitable[identity.User] - ]]: - raise NotImplementedError() - - @property - def update_user(self) -> Callable[ - [identity.UpdateUserRequest], - Union[ - identity.User, - Awaitable[identity.User] - ]]: - raise NotImplementedError() - - @property - def delete_user(self) -> Callable[ - [identity.DeleteUserRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_users(self) -> Callable[ - [identity.ListUsersRequest], - Union[ - identity.ListUsersResponse, - Awaitable[identity.ListUsersResponse] - ]]: - 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__ = ( - 'IdentityTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py deleted file mode 100644 index 332e019bd35c..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc.py +++ /dev/null @@ -1,649 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.showcase_v1beta1.types import identity -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import IdentityTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class IdentityGrpcTransport(IdentityTransport): - """gRPC backend transport for Identity. - - A simple identity service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'localhost:7469', - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'localhost:7469', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_user(self) -> Callable[ - [identity.CreateUserRequest], - identity.User]: - r"""Return a callable for the create user method over gRPC. - - Creates a user. - - Returns: - Callable[[~.CreateUserRequest], - ~.User]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_user' not in self._stubs: - self._stubs['create_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/CreateUser', - request_serializer=identity.CreateUserRequest.serialize, - response_deserializer=identity.User.deserialize, - ) - return self._stubs['create_user'] - - @property - def get_user(self) -> Callable[ - [identity.GetUserRequest], - identity.User]: - r"""Return a callable for the get user method over gRPC. - - Retrieves the User with the given uri. - - Returns: - Callable[[~.GetUserRequest], - ~.User]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_user' not in self._stubs: - self._stubs['get_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/GetUser', - request_serializer=identity.GetUserRequest.serialize, - response_deserializer=identity.User.deserialize, - ) - return self._stubs['get_user'] - - @property - def update_user(self) -> Callable[ - [identity.UpdateUserRequest], - identity.User]: - r"""Return a callable for the update user method over gRPC. - - Updates a user. - - Returns: - Callable[[~.UpdateUserRequest], - ~.User]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_user' not in self._stubs: - self._stubs['update_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/UpdateUser', - request_serializer=identity.UpdateUserRequest.serialize, - response_deserializer=identity.User.deserialize, - ) - return self._stubs['update_user'] - - @property - def delete_user(self) -> Callable[ - [identity.DeleteUserRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete user method over gRPC. - - Deletes a user, their profile, and all of their - authored messages. - - Returns: - Callable[[~.DeleteUserRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_user' not in self._stubs: - self._stubs['delete_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/DeleteUser', - request_serializer=identity.DeleteUserRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user'] - - @property - def list_users(self) -> Callable[ - [identity.ListUsersRequest], - identity.ListUsersResponse]: - r"""Return a callable for the list users method over gRPC. - - Lists all users. - - Returns: - Callable[[~.ListUsersRequest], - ~.ListUsersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_users' not in self._stubs: - self._stubs['list_users'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/ListUsers', - request_serializer=identity.ListUsersRequest.serialize, - response_deserializer=identity.ListUsersResponse.deserialize, - ) - return self._stubs['list_users'] - - def close(self): - self._logged_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'IdentityGrpcTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py deleted file mode 100644 index 0b2ce53e949b..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/grpc_asyncio.py +++ /dev/null @@ -1,755 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.showcase_v1beta1.types import identity -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import IdentityTransport, DEFAULT_CLIENT_INFO -from .grpc import IdentityGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class IdentityGrpcAsyncIOTransport(IdentityTransport): - """gRPC AsyncIO backend transport for Identity. - - A simple identity service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'localhost:7469', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'localhost:7469', - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_user(self) -> Callable[ - [identity.CreateUserRequest], - Awaitable[identity.User]]: - r"""Return a callable for the create user method over gRPC. - - Creates a user. - - Returns: - Callable[[~.CreateUserRequest], - Awaitable[~.User]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_user' not in self._stubs: - self._stubs['create_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/CreateUser', - request_serializer=identity.CreateUserRequest.serialize, - response_deserializer=identity.User.deserialize, - ) - return self._stubs['create_user'] - - @property - def get_user(self) -> Callable[ - [identity.GetUserRequest], - Awaitable[identity.User]]: - r"""Return a callable for the get user method over gRPC. - - Retrieves the User with the given uri. - - Returns: - Callable[[~.GetUserRequest], - Awaitable[~.User]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_user' not in self._stubs: - self._stubs['get_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/GetUser', - request_serializer=identity.GetUserRequest.serialize, - response_deserializer=identity.User.deserialize, - ) - return self._stubs['get_user'] - - @property - def update_user(self) -> Callable[ - [identity.UpdateUserRequest], - Awaitable[identity.User]]: - r"""Return a callable for the update user method over gRPC. - - Updates a user. - - Returns: - Callable[[~.UpdateUserRequest], - Awaitable[~.User]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_user' not in self._stubs: - self._stubs['update_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/UpdateUser', - request_serializer=identity.UpdateUserRequest.serialize, - response_deserializer=identity.User.deserialize, - ) - return self._stubs['update_user'] - - @property - def delete_user(self) -> Callable[ - [identity.DeleteUserRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete user method over gRPC. - - Deletes a user, their profile, and all of their - authored messages. - - Returns: - Callable[[~.DeleteUserRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_user' not in self._stubs: - self._stubs['delete_user'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/DeleteUser', - request_serializer=identity.DeleteUserRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user'] - - @property - def list_users(self) -> Callable[ - [identity.ListUsersRequest], - Awaitable[identity.ListUsersResponse]]: - r"""Return a callable for the list users method over gRPC. - - Lists all users. - - Returns: - Callable[[~.ListUsersRequest], - Awaitable[~.ListUsersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_users' not in self._stubs: - self._stubs['list_users'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Identity/ListUsers', - request_serializer=identity.ListUsersRequest.serialize, - response_deserializer=identity.ListUsersResponse.deserialize, - ) - return self._stubs['list_users'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_user: self._wrap_method( - self.create_user, - default_timeout=None, - client_info=client_info, - ), - self.get_user: self._wrap_method( - self.get_user, - default_retry=retries.AsyncRetry( - initial=0.2, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=5.0, - ), - default_timeout=5.0, - client_info=client_info, - ), - self.update_user: self._wrap_method( - self.update_user, - default_timeout=None, - client_info=client_info, - ), - self.delete_user: self._wrap_method( - self.delete_user, - default_timeout=None, - client_info=client_info, - ), - self.list_users: self._wrap_method( - self.list_users, - default_retry=retries.AsyncRetry( - initial=0.2, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=5.0, - ), - default_timeout=5.0, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - 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.get_iam_policy: self._wrap_method( - self.get_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.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_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.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'IdentityGrpcAsyncIOTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py deleted file mode 100644 index d76096d100ab..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest.py +++ /dev/null @@ -1,2270 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # 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.showcase_v1beta1 import _compat as rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -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 requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.showcase_v1beta1.types import identity -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseIdentityRestTransport -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 - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class IdentityRestInterceptor: - """Interceptor for Identity. - - 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 IdentityRestTransport. - - .. code-block:: python - class MyCustomIdentityInterceptor(IdentityRestInterceptor): - def pre_create_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_user(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_user(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_users(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_users(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_user(self, response): - logging.log(f"Received response: {response}") - return response - - transport = IdentityRestTransport(interceptor=MyCustomIdentityInterceptor()) - client = IdentityClient(transport=transport) - - - """ - def pre_create_user(self, request: identity.CreateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity server. - """ - return request, metadata - - def post_create_user(self, response: identity.User) -> identity.User: - """Post-rpc interceptor for create_user - - DEPRECATED. Please use the `post_create_user_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Identity server but before - it is returned to user code. This `post_create_user` interceptor runs - before the `post_create_user_with_metadata` interceptor. - """ - return response - - def post_create_user_with_metadata(self, response: identity.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_user - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Identity server but before it is returned to user code. - - We recommend only using this `post_create_user_with_metadata` - interceptor in new development instead of the `post_create_user` interceptor. - When both interceptors are used, this `post_create_user_with_metadata` interceptor runs after the - `post_create_user` interceptor. The (possibly modified) response returned by - `post_create_user` will be passed to - `post_create_user_with_metadata`. - """ - return response, metadata - - def pre_delete_user(self, request: identity.DeleteUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity server. - """ - return request, metadata - - def pre_get_user(self, request: identity.GetUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity server. - """ - return request, metadata - - def post_get_user(self, response: identity.User) -> identity.User: - """Post-rpc interceptor for get_user - - DEPRECATED. Please use the `post_get_user_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Identity server but before - it is returned to user code. This `post_get_user` interceptor runs - before the `post_get_user_with_metadata` interceptor. - """ - return response - - def post_get_user_with_metadata(self, response: identity.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_user - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Identity server but before it is returned to user code. - - We recommend only using this `post_get_user_with_metadata` - interceptor in new development instead of the `post_get_user` interceptor. - When both interceptors are used, this `post_get_user_with_metadata` interceptor runs after the - `post_get_user` interceptor. The (possibly modified) response returned by - `post_get_user` will be passed to - `post_get_user_with_metadata`. - """ - return response, metadata - - def pre_list_users(self, request: identity.ListUsersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_users - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity server. - """ - return request, metadata - - def post_list_users(self, response: identity.ListUsersResponse) -> identity.ListUsersResponse: - """Post-rpc interceptor for list_users - - DEPRECATED. Please use the `post_list_users_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Identity server but before - it is returned to user code. This `post_list_users` interceptor runs - before the `post_list_users_with_metadata` interceptor. - """ - return response - - def post_list_users_with_metadata(self, response: identity.ListUsersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_users - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Identity server but before it is returned to user code. - - We recommend only using this `post_list_users_with_metadata` - interceptor in new development instead of the `post_list_users` interceptor. - When both interceptors are used, this `post_list_users_with_metadata` interceptor runs after the - `post_list_users` interceptor. The (possibly modified) response returned by - `post_list_users` will be passed to - `post_list_users_with_metadata`. - """ - return response, metadata - - def pre_update_user(self, request: identity.UpdateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity server. - """ - return request, metadata - - def post_update_user(self, response: identity.User) -> identity.User: - """Post-rpc interceptor for update_user - - DEPRECATED. Please use the `post_update_user_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Identity server but before - it is returned to user code. This `post_update_user` interceptor runs - before the `post_update_user_with_metadata` interceptor. - """ - return response - - def post_update_user_with_metadata(self, response: identity.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[identity.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_user - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Identity server but before it is returned to user code. - - We recommend only using this `post_update_user_with_metadata` - interceptor in new development instead of the `post_update_user` interceptor. - When both interceptors are used, this `post_update_user_with_metadata` interceptor runs after the - `post_update_user` interceptor. The (possibly modified) response returned by - `post_update_user` will be passed to - `post_update_user_with_metadata`. - """ - return response, metadata - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Identity 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 Identity server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class IdentityRestStub: - _session: AuthorizedSession - _host: str - _interceptor: IdentityRestInterceptor - - -class IdentityRestTransport(_BaseIdentityRestTransport): - """REST backend synchronous transport for Identity. - - A simple identity service. - - This 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 = 'localhost:7469', - 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[IdentityRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[IdentityRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or IdentityRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateUser(_BaseIdentityRestTransport._BaseCreateUser, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.CreateUser") - - @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: identity.CreateUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> identity.User: - r"""Call the create user method over HTTP. - - Args: - request (~.identity.CreateUserRequest): - The request object. The request message for the - google.showcase.v1beta1.Identity\CreateUser - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.identity.User: - A user. - """ - - http_options = _BaseIdentityRestTransport._BaseCreateUser._get_http_options() - request, metadata = self._interceptor.pre_create_user(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseCreateUser, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.CreateUser", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "CreateUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._CreateUser._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 = identity.User() - pb_resp = identity.User.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_user(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = identity.User.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityClient.create_user", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "CreateUser", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteUser(_BaseIdentityRestTransport._BaseDeleteUser, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.DeleteUser") - - @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: identity.DeleteUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete user method over HTTP. - - Args: - request (~.identity.DeleteUserRequest): - The request object. The request message for the - google.showcase.v1beta1.Identity\DeleteUser - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseIdentityRestTransport._BaseDeleteUser._get_http_options() - request, metadata = self._interceptor.pre_delete_user(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseDeleteUser, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.DeleteUser", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "DeleteUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._DeleteUser._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetUser(_BaseIdentityRestTransport._BaseGetUser, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.GetUser") - - @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: identity.GetUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> identity.User: - r"""Call the get user method over HTTP. - - Args: - request (~.identity.GetUserRequest): - The request object. The request message for the - google.showcase.v1beta1.Identity\GetUser - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.identity.User: - A user. - """ - - http_options = _BaseIdentityRestTransport._BaseGetUser._get_http_options() - request, metadata = self._interceptor.pre_get_user(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseGetUser, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.GetUser", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._GetUser._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 = identity.User() - pb_resp = identity.User.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_user(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = identity.User.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityClient.get_user", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetUser", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListUsers(_BaseIdentityRestTransport._BaseListUsers, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.ListUsers") - - @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: identity.ListUsersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> identity.ListUsersResponse: - r"""Call the list users method over HTTP. - - Args: - request (~.identity.ListUsersRequest): - The request object. The request message for the - google.showcase.v1beta1.Identity\ListUsers - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.identity.ListUsersResponse: - The response message for the - google.showcase.v1beta1.Identity\ListUsers - method. - - """ - - http_options = _BaseIdentityRestTransport._BaseListUsers._get_http_options() - request, metadata = self._interceptor.pre_list_users(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseListUsers, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.ListUsers", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "ListUsers", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._ListUsers._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 = identity.ListUsersResponse() - pb_resp = identity.ListUsersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_users(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_users_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = identity.ListUsersResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityClient.list_users", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "ListUsers", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateUser(_BaseIdentityRestTransport._BaseUpdateUser, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.UpdateUser") - - @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: identity.UpdateUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> identity.User: - r"""Call the update user method over HTTP. - - Args: - request (~.identity.UpdateUserRequest): - The request object. The request message for the - google.showcase.v1beta1.Identity\UpdateUser - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.identity.User: - A user. - """ - - http_options = _BaseIdentityRestTransport._BaseUpdateUser._get_http_options() - request, metadata = self._interceptor.pre_update_user(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseUpdateUser, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.UpdateUser", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "UpdateUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._UpdateUser._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 = identity.User() - pb_resp = identity.User.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_user(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = identity.User.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityClient.update_user", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "UpdateUser", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_user(self) -> Callable[ - [identity.CreateUserRequest], - identity.User]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_user(self) -> Callable[ - [identity.DeleteUserRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_user(self) -> Callable[ - [identity.GetUserRequest], - identity.User]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_users(self) -> Callable[ - [identity.ListUsersRequest], - identity.ListUsersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_user(self) -> Callable[ - [identity.UpdateUserRequest], - identity.User]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseIdentityRestTransport._BaseListLocations, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseIdentityRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseListLocations, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.ListLocations", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "ListLocations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.ListLocations", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "ListLocations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseIdentityRestTransport._BaseGetLocation, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseIdentityRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseGetLocation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.GetLocation", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetLocation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.GetLocation", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetLocation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseIdentityRestTransport._BaseSetIamPolicy, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseIdentityRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseSetIamPolicy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.SetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "SetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseIdentityRestTransport._BaseGetIamPolicy, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseIdentityRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseGetIamPolicy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.GetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseIdentityRestTransport._BaseTestIamPermissions, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseIdentityRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseTestIamPermissions, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.TestIamPermissions", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "TestIamPermissions", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseIdentityRestTransport._BaseListOperations, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseIdentityRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseListOperations, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.ListOperations", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.ListOperations", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseIdentityRestTransport._BaseGetOperation, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseIdentityRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseGetOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.GetOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.IdentityAsyncClient.GetOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseIdentityRestTransport._BaseDeleteOperation, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseIdentityRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseDeleteOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.DeleteOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._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 cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseIdentityRestTransport._BaseCancelOperation, IdentityRestStub): - def __hash__(self): - return hash("IdentityRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseIdentityRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseIdentityRestTransport._BaseCancelOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.IdentityClient.CancelOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Identity", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = IdentityRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'IdentityRestTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py deleted file mode 100644 index 01e9d7bd350f..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/identity/transports/rest_base.py +++ /dev/null @@ -1,354 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 IdentityTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.showcase_v1beta1.types import identity -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseIdentityRestTransport(IdentityTransport): - """Base REST backend transport for Identity. - - 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 = 'localhost:7469', - 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: 'localhost:7469'). - 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 _BaseCreateUser: - 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': '/v1beta1/users', - 'body': '*', - }, - ] - return http_options - - class _BaseDeleteUser: - 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': '/v1beta1/{name=users/*}', - }, - ] - return http_options - - class _BaseGetUser: - 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': '/v1beta1/{name=users/*}', - }, - ] - return http_options - - class _BaseListUsers: - 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': '/v1beta1/users', - }, - ] - return http_options - - class _BaseUpdateUser: - 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': '/v1beta1/{user.name=users/*}', - 'body': 'user', - }, - ] - return http_options - - 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': '/v1beta1/{name=projects/*}/locations', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=projects/*/locations/*}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=sequences/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=rooms/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=sequences/*}:getIamPolicy', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=sequences/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - pass - - 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': '/v1beta1/operations', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}:cancel', - }, - ] - return http_options - - pass - - -__all__=( - '_BaseIdentityRestTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py deleted file mode 100644 index 398d1b81e782..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 MessagingClient -from .async_client import MessagingAsyncClient - -__all__ = ( - 'MessagingClient', - 'MessagingAsyncClient', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py deleted file mode 100644 index 807a1d5f52aa..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/async_client.py +++ /dev/null @@ -1,2367 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import uuid - -from google.showcase_v1beta1 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 -import google.protobuf - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.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.showcase_v1beta1.services.messaging import pagers -from google.showcase_v1beta1.types import messaging -import google.api_core.operation as operation # type: ignore -import google.api_core.operation_async as operation_async # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import MessagingTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import MessagingGrpcAsyncIOTransport -from .client import MessagingClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class MessagingAsyncClient: - """A simple messaging service that implements chat rooms and - profile posts. - This messaging service showcases the features that API clients - generated by gapic-generators implement. - """ - - _client: MessagingClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = MessagingClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = MessagingClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = MessagingClient._DEFAULT_UNIVERSE - - blurb_path = staticmethod(MessagingClient.blurb_path) - parse_blurb_path = staticmethod(MessagingClient.parse_blurb_path) - room_path = staticmethod(MessagingClient.room_path) - parse_room_path = staticmethod(MessagingClient.parse_room_path) - user_path = staticmethod(MessagingClient.user_path) - parse_user_path = staticmethod(MessagingClient.parse_user_path) - common_billing_account_path = staticmethod(MessagingClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(MessagingClient.parse_common_billing_account_path) - common_folder_path = staticmethod(MessagingClient.common_folder_path) - parse_common_folder_path = staticmethod(MessagingClient.parse_common_folder_path) - common_organization_path = staticmethod(MessagingClient.common_organization_path) - parse_common_organization_path = staticmethod(MessagingClient.parse_common_organization_path) - common_project_path = staticmethod(MessagingClient.common_project_path) - parse_common_project_path = staticmethod(MessagingClient.parse_common_project_path) - common_location_path = staticmethod(MessagingClient.common_location_path) - parse_common_location_path = staticmethod(MessagingClient.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: - MessagingAsyncClient: The constructed client. - """ - sa_info_func = ( - MessagingClient.from_service_account_info.__func__ # type: ignore - ) - return sa_info_func(MessagingAsyncClient, info, *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: - MessagingAsyncClient: The constructed client. - """ - sa_file_func = ( - MessagingClient.from_service_account_file.__func__ # type: ignore - ) - return sa_file_func(MessagingAsyncClient, filename, *args, **kwargs) - - 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 MessagingClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> MessagingTransport: - """Returns the transport used by the client instance. - - Returns: - MessagingTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self) -> str: - """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 = MessagingClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MessagingTransport, Callable[..., MessagingTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the messaging 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,MessagingTransport,Callable[..., MessagingTransport]]]): - 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 MessagingTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - 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 = MessagingClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.showcase_v1beta1.MessagingAsyncClient`.", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.showcase.v1beta1.Messaging", - "credentialsType": None, - } - ) - - async def create_room(self, - request: Optional[Union[messaging.CreateRoomRequest, dict]] = None, - *, - display_name: Optional[str] = None, - description: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Room: - r"""Creates a room. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_create_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateRoomRequest( - ) - - # Make the request - response = await client.create_room(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.CreateRoomRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\CreateRoom - method. - display_name (:class:`str`): - The human readable name of the chat - room. - - This corresponds to the ``room.display_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - description (:class:`str`): - The description of the chat room. - This corresponds to the ``room.description`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Room: - A chat room. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [display_name, description] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.CreateRoomRequest): - request = messaging.CreateRoomRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if display_name is not None: - request.room.display_name = display_name - if description is not None: - request.room.description = description - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_room] - - # 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_room(self, - request: Optional[Union[messaging.GetRoomRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Room: - r"""Retrieves the Room with the given resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_get_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetRoomRequest( - name="name_value", - ) - - # Make the request - response = await client.get_room(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.GetRoomRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\GetRoom - method. - name (:class:`str`): - The resource name of the requested - room. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Room: - A chat room. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.GetRoomRequest): - request = messaging.GetRoomRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_room] - - # Certain 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_room(self, - request: Optional[Union[messaging.UpdateRoomRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Room: - r"""Updates a room. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_update_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateRoomRequest( - ) - - # Make the request - response = await client.update_room(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.UpdateRoomRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\UpdateRoom - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Room: - A chat room. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.UpdateRoomRequest): - request = messaging.UpdateRoomRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_room] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("room.name", request.room.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_room(self, - request: Optional[Union[messaging.DeleteRoomRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a room and all of its blurbs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_delete_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteRoomRequest( - name="name_value", - ) - - # Make the request - await client.delete_room(request=request) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.DeleteRoomRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\DeleteRoom - method. - name (:class:`str`): - The resource name of the requested - room. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.DeleteRoomRequest): - request = messaging.DeleteRoomRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_room] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_rooms(self, - request: Optional[Union[messaging.ListRoomsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListRoomsAsyncPager: - r"""Lists all chat rooms. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_list_rooms(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListRoomsRequest( - ) - - # Make the request - page_result = client.list_rooms(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.ListRoomsRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\ListRooms - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.messaging.pagers.ListRoomsAsyncPager: - The response message for the - google.showcase.v1beta1.Messaging\ListRooms - method. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.ListRoomsRequest): - request = messaging.ListRoomsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_rooms] - - # 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.ListRoomsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_blurb(self, - request: Optional[Union[messaging.CreateBlurbRequest, dict]] = None, - *, - parent: Optional[str] = None, - user: Optional[str] = None, - text: Optional[str] = None, - image: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Blurb: - r"""Creates a blurb. If the parent is a room, the blurb - is understood to be a message in that room. If the - parent is a profile, the blurb is understood to be a - post on the profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_create_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_blurb(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.CreateBlurbRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\CreateBlurb - method. - parent (:class:`str`): - The resource name of the chat room or - user profile that this blurb will be - tied to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user (:class:`str`): - The resource name of the blurb's - author. - - This corresponds to the ``blurb.user`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - text (:class:`str`): - The textual content of this blurb. - This corresponds to the ``blurb.text`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - image (:class:`bytes`): - The image content of this blurb. - This corresponds to the ``blurb.image`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, user, text, image] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.CreateBlurbRequest): - request = messaging.CreateBlurbRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user is not None: - request.blurb.user = user - if text is not None: - request.blurb.text = text - if image is not None: - request.blurb.image = image - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_blurb] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_blurb(self, - request: Optional[Union[messaging.GetBlurbRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Blurb: - r"""Retrieves the Blurb with the given resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_get_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetBlurbRequest( - name="name_value", - ) - - # Make the request - response = await client.get_blurb(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.GetBlurbRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\GetBlurb - method. - name (:class:`str`): - The resource name of the requested - blurb. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.GetBlurbRequest): - request = messaging.GetBlurbRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_blurb] - - # Certain 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_blurb(self, - request: Optional[Union[messaging.UpdateBlurbRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Blurb: - r"""Updates a blurb. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_update_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateBlurbRequest( - ) - - # Make the request - response = await client.update_blurb(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.UpdateBlurbRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\UpdateBlurb - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.UpdateBlurbRequest): - request = messaging.UpdateBlurbRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_blurb] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("blurb.name", request.blurb.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_blurb(self, - request: Optional[Union[messaging.DeleteBlurbRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a blurb. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_delete_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteBlurbRequest( - name="name_value", - ) - - # Make the request - await client.delete_blurb(request=request) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.DeleteBlurbRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\DeleteBlurb - method. - name (:class:`str`): - The resource name of the requested - blurb. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.DeleteBlurbRequest): - request = messaging.DeleteBlurbRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_blurb] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_blurbs(self, - request: Optional[Union[messaging.ListBlurbsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBlurbsAsyncPager: - r"""Lists blurbs for a specific chat room or user profile - depending on the parent resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_list_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListBlurbsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_blurbs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.ListBlurbsRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\ListBlurbs - method. - parent (:class:`str`): - The resource name of the requested - room or profile whos blurbs to list. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.messaging.pagers.ListBlurbsAsyncPager: - The response message for the - google.showcase.v1beta1.Messaging\ListBlurbs - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.ListBlurbsRequest): - request = messaging.ListBlurbsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_blurbs] - - # Certain 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.ListBlurbsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_blurbs(self, - request: Optional[Union[messaging.SearchBlurbsRequest, dict]] = None, - *, - parent: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""This method searches through all blurbs across all - rooms and profiles for blurbs containing to words found - in the query. Only posts that contain an exact match of - a queried word will be returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_search_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.SearchBlurbsRequest( - query="query_value", - ) - - # Make the request - operation = await client.search_blurbs(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.SearchBlurbsRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\SearchBlurbs - method. - parent (:class:`str`): - The rooms or profiles to search. If unset, - ``SearchBlurbs`` will search all rooms and all profiles. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - The query used to search for blurbs - containing to words of this string. Only - posts that contain an exact match of a - queried word will be returned. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.showcase_v1beta1.types.SearchBlurbsResponse` The operation response message for the - google.showcase.v1beta1.MessagingSearchBlurbs method. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, query] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.SearchBlurbsRequest): - request = messaging.SearchBlurbsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_blurbs] - - # Certain 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, - messaging.SearchBlurbsResponse, - metadata_type=messaging.SearchBlurbsMetadata, - ) - - # Done; return the response. - return response - - def stream_blurbs(self, - request: Optional[Union[messaging.StreamBlurbsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[messaging.StreamBlurbsResponse]]: - r"""This returns a stream that emits the blurbs that are - created for a particular chat room or user profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_stream_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.StreamBlurbsRequest( - name="name_value", - ) - - # Make the request - stream = await client.stream_blurbs(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.showcase_v1beta1.types.StreamBlurbsRequest, dict]]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - AsyncIterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: - The response message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.StreamBlurbsRequest): - request = messaging.StreamBlurbsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.stream_blurbs] - - # Certain 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 = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def send_blurbs(self, - requests: Optional[AsyncIterator[messaging.CreateBlurbRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.SendBlurbsResponse: - r"""This is a stream to create multiple blurbs. If an - invalid blurb is requested to be created, the stream - will close with an error. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_send_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.CreateBlurbRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = await client.send_blurbs(requests=request_generator()) - - # Handle the response - print(response) - - Args: - requests (AsyncIterator[`google.showcase_v1beta1.types.CreateBlurbRequest`]): - The request object AsyncIterator. The request message for the - google.showcase.v1beta1.Messaging\CreateBlurb - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.SendBlurbsResponse: - The response message for the - google.showcase.v1beta1.Messaging\SendBlurbs - method. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.send_blurbs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def connect(self, - requests: Optional[AsyncIterator[messaging.ConnectRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[messaging.StreamBlurbsResponse]]: - r"""This method starts a bidirectional stream that - receives all blurbs that are being created after the - stream has started and sends requests to create blurbs. - If an invalid blurb is requested to be created, the - stream will close with an error. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - async def sample_connect(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ConnectRequest( - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.ConnectRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.connect(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.showcase_v1beta1.types.ConnectRequest`]): - The request object AsyncIterator. The request message for the - google.showcase.v1beta1.Messaging\Connect - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - AsyncIterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: - The response message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.connect] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.DeleteOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.DeleteOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.CancelOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.CancelOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.SetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.GetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.TestIamPermissionsRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.GetLocationRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.GetLocationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.ListLocationsRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.ListLocationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "MessagingAsyncClient": - 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__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "MessagingAsyncClient", -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py deleted file mode 100644 index bfa9df3e0ffd..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/client.py +++ /dev/null @@ -1,2811 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast -import uuid -import warnings - -from google.showcase_v1beta1 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 -import google.protobuf - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.cloud.location import locations_pb2 # type: ignore -from google.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.showcase_v1beta1.services.messaging import pagers -from google.showcase_v1beta1.types import messaging -import google.api_core.operation as operation # type: ignore -import google.api_core.operation_async as operation_async # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import MessagingTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import MessagingGrpcTransport -from .transports.grpc_asyncio import MessagingGrpcAsyncIOTransport -from .transports.rest import MessagingRestTransport - - -class MessagingClientMeta(type): - """Metaclass for the Messaging 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[MessagingTransport]] - _transport_registry["grpc"] = MessagingGrpcTransport - _transport_registry["grpc_asyncio"] = MessagingGrpcAsyncIOTransport - _transport_registry["rest"] = MessagingRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[MessagingTransport]: - """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 MessagingClient(metaclass=MessagingClientMeta): - """A simple messaging service that implements chat rooms and - profile posts. - This messaging service showcases the features that API clients - generated by gapic-generators implement. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: - """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: - Optional[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) - if m is None: - # Could not parse api_endpoint; return as-is. - return 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 = "localhost:7469" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "localhost:7469" - _DEFAULT_UNIVERSE = "googleapis.com" - - @staticmethod - def _use_client_cert_effective(): - """Returns whether client certificate should be used for mTLS if the - google-auth version supports should_use_client_cert automatic mTLS enablement. - - Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. - - Returns: - bool: whether client certificate should be used for mTLS - Raises: - ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) - """ - # check if google-auth version supports should_use_client_cert for automatic mTLS enablement - if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER - return mtls.should_use_client_cert() - else: # pragma: NO COVER - # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - if use_client_cert_str not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" - " either `true` or `false`" - ) - return use_client_cert_str == "true" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - MessagingClient: 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: - MessagingClient: 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) -> MessagingTransport: - """Returns the transport used by the client instance. - - Returns: - MessagingTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def blurb_path(user: str,legacy_user: str,blurb: str,) -> str: - """Returns a fully-qualified blurb string.""" - return "users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}".format(user=user, legacy_user=legacy_user, blurb=blurb, ) - - @staticmethod - def parse_blurb_path(path: str) -> Dict[str,str]: - """Parses a blurb path into its component segments.""" - m = re.match(r"^users/(?P.+?)/profile/blurbs/legacy/(?P.+?)~(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def room_path(room: str,) -> str: - """Returns a fully-qualified room string.""" - return "rooms/{room}".format(room=room, ) - - @staticmethod - def parse_room_path(path: str) -> Dict[str,str]: - """Parses a room path into its component segments.""" - m = re.match(r"^rooms/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_path(user: str,) -> str: - """Returns a fully-qualified user string.""" - return "users/{user}".format(user=user, ) - - @staticmethod - def parse_user_path(path: str) -> Dict[str,str]: - """Parses a user path into its component segments.""" - m = re.match(r"^users/(?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 = MessagingClient._use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = MessagingClient._use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert, use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: - """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 = MessagingClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = MessagingClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = MessagingClient._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 = MessagingClient._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 - - @staticmethod - def _setup_request_id(request, field_name: str, is_proto3_optional: bool): - """Populate a UUID4 field in the request if it is not already set. - - Args: - request (Union[google.protobuf.message.Message, dict]): The request object. - field_name (str): The name of the field to populate. - is_proto3_optional (bool): Whether the field is proto3 optional. - """ - if isinstance(request, dict): - if is_proto3_optional: - if field_name not in request: - request[field_name] = str(uuid.uuid4()) - elif not request.get(field_name): - request[field_name] = str(uuid.uuid4()) - return - - if is_proto3_optional: - try: - # Pure protobuf messages - if not request.HasField(field_name): - setattr(request, field_name, str(uuid.uuid4())) - except (AttributeError, ValueError): - # Proto-plus messages or other objects - if field_name not in request: - setattr(request, field_name, str(uuid.uuid4())) - else: - if not getattr(request, field_name): - setattr(request, field_name, str(uuid.uuid4())) - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self) -> str: - """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, MessagingTransport, Callable[..., MessagingTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the messaging client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. 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,MessagingTransport,Callable[..., MessagingTransport]]]): - 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 MessagingTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - 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 = MessagingClient._read_environment_variables() - self._client_cert_source = MessagingClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = MessagingClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint: str = "" # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, MessagingTransport) - if transport_provided: - # transport is a MessagingTransport 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(MessagingTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - MessagingClient._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[MessagingTransport], Callable[..., MessagingTransport]] = ( - MessagingClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., MessagingTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.showcase_v1beta1.MessagingClient`.", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.showcase.v1beta1.Messaging", - "credentialsType": None, - } - ) - - def create_room(self, - request: Optional[Union[messaging.CreateRoomRequest, dict]] = None, - *, - display_name: Optional[str] = None, - description: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Room: - r"""Creates a room. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_create_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateRoomRequest( - ) - - # Make the request - response = client.create_room(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.CreateRoomRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\CreateRoom - method. - display_name (str): - The human readable name of the chat - room. - - This corresponds to the ``room.display_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - description (str): - The description of the chat room. - This corresponds to the ``room.description`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Room: - A chat room. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [display_name, description] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.CreateRoomRequest): - request = messaging.CreateRoomRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if display_name is not None: - request.room.display_name = display_name - if description is not None: - request.room.description = description - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_room] - - # 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_room(self, - request: Optional[Union[messaging.GetRoomRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Room: - r"""Retrieves the Room with the given resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_get_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetRoomRequest( - name="name_value", - ) - - # Make the request - response = client.get_room(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.GetRoomRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\GetRoom - method. - name (str): - The resource name of the requested - room. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Room: - A chat room. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.GetRoomRequest): - request = messaging.GetRoomRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_room] - - # Certain 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_room(self, - request: Optional[Union[messaging.UpdateRoomRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Room: - r"""Updates a room. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_update_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateRoomRequest( - ) - - # Make the request - response = client.update_room(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.UpdateRoomRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\UpdateRoom - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Room: - A chat room. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.UpdateRoomRequest): - request = messaging.UpdateRoomRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_room] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("room.name", request.room.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_room(self, - request: Optional[Union[messaging.DeleteRoomRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a room and all of its blurbs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_delete_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteRoomRequest( - name="name_value", - ) - - # Make the request - client.delete_room(request=request) - - Args: - request (Union[google.showcase_v1beta1.types.DeleteRoomRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\DeleteRoom - method. - name (str): - The resource name of the requested - room. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.DeleteRoomRequest): - request = messaging.DeleteRoomRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_room] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_rooms(self, - request: Optional[Union[messaging.ListRoomsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListRoomsPager: - r"""Lists all chat rooms. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_list_rooms(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListRoomsRequest( - ) - - # Make the request - page_result = client.list_rooms(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.ListRoomsRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\ListRooms - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.messaging.pagers.ListRoomsPager: - The response message for the - google.showcase.v1beta1.Messaging\ListRooms - method. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.ListRoomsRequest): - request = messaging.ListRoomsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_rooms] - - # 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.ListRoomsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_blurb(self, - request: Optional[Union[messaging.CreateBlurbRequest, dict]] = None, - *, - parent: Optional[str] = None, - user: Optional[str] = None, - text: Optional[str] = None, - image: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Blurb: - r"""Creates a blurb. If the parent is a room, the blurb - is understood to be a message in that room. If the - parent is a profile, the blurb is understood to be a - post on the profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_create_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_blurb(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.CreateBlurbRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\CreateBlurb - method. - parent (str): - The resource name of the chat room or - user profile that this blurb will be - tied to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user (str): - The resource name of the blurb's - author. - - This corresponds to the ``blurb.user`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - text (str): - The textual content of this blurb. - This corresponds to the ``blurb.text`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - image (bytes): - The image content of this blurb. - This corresponds to the ``blurb.image`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, user, text, image] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.CreateBlurbRequest): - request = messaging.CreateBlurbRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user is not None: - request.blurb.user = user - if text is not None: - request.blurb.text = text - if image is not None: - request.blurb.image = image - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_blurb] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_blurb(self, - request: Optional[Union[messaging.GetBlurbRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Blurb: - r"""Retrieves the Blurb with the given resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_get_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetBlurbRequest( - name="name_value", - ) - - # Make the request - response = client.get_blurb(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.GetBlurbRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\GetBlurb - method. - name (str): - The resource name of the requested - blurb. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.GetBlurbRequest): - request = messaging.GetBlurbRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_blurb] - - # Certain 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_blurb(self, - request: Optional[Union[messaging.UpdateBlurbRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.Blurb: - r"""Updates a blurb. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_update_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateBlurbRequest( - ) - - # Make the request - response = client.update_blurb(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.UpdateBlurbRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\UpdateBlurb - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.UpdateBlurbRequest): - request = messaging.UpdateBlurbRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_blurb] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("blurb.name", request.blurb.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_blurb(self, - request: Optional[Union[messaging.DeleteBlurbRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a blurb. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_delete_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteBlurbRequest( - name="name_value", - ) - - # Make the request - client.delete_blurb(request=request) - - Args: - request (Union[google.showcase_v1beta1.types.DeleteBlurbRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\DeleteBlurb - method. - name (str): - The resource name of the requested - blurb. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.DeleteBlurbRequest): - request = messaging.DeleteBlurbRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_blurb] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_blurbs(self, - request: Optional[Union[messaging.ListBlurbsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBlurbsPager: - r"""Lists blurbs for a specific chat room or user profile - depending on the parent resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_list_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListBlurbsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_blurbs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.ListBlurbsRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\ListBlurbs - method. - parent (str): - The resource name of the requested - room or profile whos blurbs to list. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.services.messaging.pagers.ListBlurbsPager: - The response message for the - google.showcase.v1beta1.Messaging\ListBlurbs - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.ListBlurbsRequest): - request = messaging.ListBlurbsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_blurbs] - - # Certain 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.ListBlurbsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_blurbs(self, - request: Optional[Union[messaging.SearchBlurbsRequest, dict]] = None, - *, - parent: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""This method searches through all blurbs across all - rooms and profiles for blurbs containing to words found - in the query. Only posts that contain an exact match of - a queried word will be returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_search_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.SearchBlurbsRequest( - query="query_value", - ) - - # Make the request - operation = client.search_blurbs(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.SearchBlurbsRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\SearchBlurbs - method. - parent (str): - The rooms or profiles to search. If unset, - ``SearchBlurbs`` will search all rooms and all profiles. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - The query used to search for blurbs - containing to words of this string. Only - posts that contain an exact match of a - queried word will be returned. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.showcase_v1beta1.types.SearchBlurbsResponse` The operation response message for the - google.showcase.v1beta1.MessagingSearchBlurbs method. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, query] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.SearchBlurbsRequest): - request = messaging.SearchBlurbsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_blurbs] - - # Certain 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, - messaging.SearchBlurbsResponse, - metadata_type=messaging.SearchBlurbsMetadata, - ) - - # Done; return the response. - return response - - def stream_blurbs(self, - request: Optional[Union[messaging.StreamBlurbsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[messaging.StreamBlurbsResponse]: - r"""This returns a stream that emits the blurbs that are - created for a particular chat room or user profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_stream_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.StreamBlurbsRequest( - name="name_value", - ) - - # Make the request - stream = client.stream_blurbs(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.showcase_v1beta1.types.StreamBlurbsRequest, dict]): - The request object. The request message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: - The response message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, messaging.StreamBlurbsRequest): - request = messaging.StreamBlurbsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stream_blurbs] - - # Certain 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 send_blurbs(self, - requests: Optional[Iterator[messaging.CreateBlurbRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> messaging.SendBlurbsResponse: - r"""This is a stream to create multiple blurbs. If an - invalid blurb is requested to be created, the stream - will close with an error. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_send_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.CreateBlurbRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = client.send_blurbs(requests=request_generator()) - - # Handle the response - print(response) - - Args: - requests (Iterator[google.showcase_v1beta1.types.CreateBlurbRequest]): - The request object iterator. The request message for the - google.showcase.v1beta1.Messaging\CreateBlurb - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.showcase_v1beta1.types.SendBlurbsResponse: - The response message for the - google.showcase.v1beta1.Messaging\SendBlurbs - method. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.send_blurbs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def connect(self, - requests: Optional[Iterator[messaging.ConnectRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[messaging.StreamBlurbsResponse]: - r"""This method starts a bidirectional stream that - receives all blurbs that are being created after the - stream has started and sends requests to create blurbs. - If an invalid blurb is requested to be created, the - stream will close with an error. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import showcase_v1beta1 - - def sample_connect(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ConnectRequest( - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.ConnectRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.connect(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.showcase_v1beta1.types.ConnectRequest]): - The request object iterator. The request message for the - google.showcase.v1beta1.Messaging\Connect - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]: - The response message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.connect] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "MessagingClient": - 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_operation( - self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def delete_operation( - self, - request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.DeleteOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.DeleteOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.CancelOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.CancelOperationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.SetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_iam_policy( - self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.GetIamPolicyRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def test_iam_permissions( - self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = iam_policy_pb2.TestIamPermissionsRequest() - elif isinstance(request, dict): - request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) - else: - request_pb = 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_pb.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_location( - self, - request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.GetLocationRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.GetLocationRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def list_locations( - self, - request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = locations_pb2.ListLocationsRequest() - elif isinstance(request, dict): - request_pb = locations_pb2.ListLocationsRequest(**request) - else: - request_pb = 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_pb.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "MessagingClient", -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py deleted file mode 100644 index 711bbecfdb1d..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/pagers.py +++ /dev/null @@ -1,305 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1.types import messaging - - -class ListRoomsPager: - """A pager for iterating through ``list_rooms`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.ListRoomsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``rooms`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListRooms`` requests and continue to iterate - through the ``rooms`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.ListRoomsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., messaging.ListRoomsResponse], - request: messaging.ListRoomsRequest, - response: messaging.ListRoomsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.ListRoomsRequest): - The initial request object. - response (google.showcase_v1beta1.types.ListRoomsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = messaging.ListRoomsRequest(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[messaging.ListRoomsResponse]: - 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[messaging.Room]: - for page in self.pages: - yield from page.rooms - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRoomsAsyncPager: - """A pager for iterating through ``list_rooms`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.ListRoomsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``rooms`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListRooms`` requests and continue to iterate - through the ``rooms`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.ListRoomsResponse` - attributes are available on the 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[messaging.ListRoomsResponse]], - request: messaging.ListRoomsRequest, - response: messaging.ListRoomsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.ListRoomsRequest): - The initial request object. - response (google.showcase_v1beta1.types.ListRoomsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = messaging.ListRoomsRequest(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[messaging.ListRoomsResponse]: - 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[messaging.Room]: - async def async_generator(): - async for page in self.pages: - for response in page.rooms: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBlurbsPager: - """A pager for iterating through ``list_blurbs`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.ListBlurbsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``blurbs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBlurbs`` requests and continue to iterate - through the ``blurbs`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.ListBlurbsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., messaging.ListBlurbsResponse], - request: messaging.ListBlurbsRequest, - response: messaging.ListBlurbsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.ListBlurbsRequest): - The initial request object. - response (google.showcase_v1beta1.types.ListBlurbsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = messaging.ListBlurbsRequest(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[messaging.ListBlurbsResponse]: - 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[messaging.Blurb]: - for page in self.pages: - yield from page.blurbs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBlurbsAsyncPager: - """A pager for iterating through ``list_blurbs`` requests. - - This class thinly wraps an initial - :class:`google.showcase_v1beta1.types.ListBlurbsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``blurbs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBlurbs`` requests and continue to iterate - through the ``blurbs`` field on the - corresponding responses. - - All the usual :class:`google.showcase_v1beta1.types.ListBlurbsResponse` - attributes are available on the 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[messaging.ListBlurbsResponse]], - request: messaging.ListBlurbsRequest, - response: messaging.ListBlurbsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.showcase_v1beta1.types.ListBlurbsRequest): - The initial request object. - response (google.showcase_v1beta1.types.ListBlurbsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = messaging.ListBlurbsRequest(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[messaging.ListBlurbsResponse]: - 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[messaging.Blurb]: - async def async_generator(): - async for page in self.pages: - for response in page.blurbs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst deleted file mode 100644 index 1d6729e40638..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/README.rst +++ /dev/null @@ -1,10 +0,0 @@ - -transport inheritance structure -_______________________________ - -``MessagingTransport`` is the ABC for all transports. - -- public child ``MessagingGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). -- public child ``MessagingGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). -- private child ``_BaseMessagingRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). -- public child ``MessagingRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py deleted file mode 100644 index cffcf10c086d..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 MessagingTransport -from .grpc import MessagingGrpcTransport -from .grpc_asyncio import MessagingGrpcAsyncIOTransport -from .rest import MessagingRestTransport -from .rest import MessagingRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[MessagingTransport]] -_transport_registry['grpc'] = MessagingGrpcTransport -_transport_registry['grpc_asyncio'] = MessagingGrpcAsyncIOTransport -_transport_registry['rest'] = MessagingRestTransport - -__all__ = ( - 'MessagingTransport', - 'MessagingGrpcTransport', - 'MessagingGrpcAsyncIOTransport', - 'MessagingRestTransport', - 'MessagingRestInterceptor', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py deleted file mode 100644 index 56895799a573..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/base.py +++ /dev/null @@ -1,542 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.showcase_v1beta1 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 -import google.protobuf - -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.showcase_v1beta1.types import messaging -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class MessagingTransport(abc.ABC): - """Abstract transport class for Messaging.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'localhost:7469' - - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - """ - - # 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) - # 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 - - self._wrapped_methods: Dict[Callable, Callable] = {} - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_room: gapic_v1.method.wrap_method( - self.create_room, - default_timeout=None, - client_info=client_info, - ), - self.get_room: gapic_v1.method.wrap_method( - self.get_room, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.update_room: gapic_v1.method.wrap_method( - self.update_room, - default_timeout=None, - client_info=client_info, - ), - self.delete_room: gapic_v1.method.wrap_method( - self.delete_room, - default_timeout=None, - client_info=client_info, - ), - self.list_rooms: gapic_v1.method.wrap_method( - self.list_rooms, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.create_blurb: gapic_v1.method.wrap_method( - self.create_blurb, - default_timeout=None, - client_info=client_info, - ), - self.get_blurb: gapic_v1.method.wrap_method( - self.get_blurb, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.update_blurb: gapic_v1.method.wrap_method( - self.update_blurb, - default_timeout=None, - client_info=client_info, - ), - self.delete_blurb: gapic_v1.method.wrap_method( - self.delete_blurb, - default_timeout=None, - client_info=client_info, - ), - self.list_blurbs: gapic_v1.method.wrap_method( - self.list_blurbs, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.search_blurbs: gapic_v1.method.wrap_method( - self.search_blurbs, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.stream_blurbs: gapic_v1.method.wrap_method( - self.stream_blurbs, - default_timeout=None, - client_info=client_info, - ), - self.send_blurbs: gapic_v1.method.wrap_method( - self.send_blurbs, - default_timeout=None, - client_info=client_info, - ), - self.connect: gapic_v1.method.wrap_method( - self.connect, - default_retry=retries.Retry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - 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.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_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.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_room(self) -> Callable[ - [messaging.CreateRoomRequest], - Union[ - messaging.Room, - Awaitable[messaging.Room] - ]]: - raise NotImplementedError() - - @property - def get_room(self) -> Callable[ - [messaging.GetRoomRequest], - Union[ - messaging.Room, - Awaitable[messaging.Room] - ]]: - raise NotImplementedError() - - @property - def update_room(self) -> Callable[ - [messaging.UpdateRoomRequest], - Union[ - messaging.Room, - Awaitable[messaging.Room] - ]]: - raise NotImplementedError() - - @property - def delete_room(self) -> Callable[ - [messaging.DeleteRoomRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_rooms(self) -> Callable[ - [messaging.ListRoomsRequest], - Union[ - messaging.ListRoomsResponse, - Awaitable[messaging.ListRoomsResponse] - ]]: - raise NotImplementedError() - - @property - def create_blurb(self) -> Callable[ - [messaging.CreateBlurbRequest], - Union[ - messaging.Blurb, - Awaitable[messaging.Blurb] - ]]: - raise NotImplementedError() - - @property - def get_blurb(self) -> Callable[ - [messaging.GetBlurbRequest], - Union[ - messaging.Blurb, - Awaitable[messaging.Blurb] - ]]: - raise NotImplementedError() - - @property - def update_blurb(self) -> Callable[ - [messaging.UpdateBlurbRequest], - Union[ - messaging.Blurb, - Awaitable[messaging.Blurb] - ]]: - raise NotImplementedError() - - @property - def delete_blurb(self) -> Callable[ - [messaging.DeleteBlurbRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_blurbs(self) -> Callable[ - [messaging.ListBlurbsRequest], - Union[ - messaging.ListBlurbsResponse, - Awaitable[messaging.ListBlurbsResponse] - ]]: - raise NotImplementedError() - - @property - def search_blurbs(self) -> Callable[ - [messaging.SearchBlurbsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def stream_blurbs(self) -> Callable[ - [messaging.StreamBlurbsRequest], - Union[ - messaging.StreamBlurbsResponse, - Awaitable[messaging.StreamBlurbsResponse] - ]]: - raise NotImplementedError() - - @property - def send_blurbs(self) -> Callable[ - [messaging.CreateBlurbRequest], - Union[ - messaging.SendBlurbsResponse, - Awaitable[messaging.SendBlurbsResponse] - ]]: - raise NotImplementedError() - - @property - def connect(self) -> Callable[ - [messaging.ConnectRequest], - Union[ - messaging.StreamBlurbsResponse, - Awaitable[messaging.StreamBlurbsResponse] - ]]: - 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__ = ( - 'MessagingTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py deleted file mode 100644 index 4d747c43ed51..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc.py +++ /dev/null @@ -1,917 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.showcase_v1beta1.types import messaging -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import MessagingTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class MessagingGrpcTransport(MessagingTransport): - """gRPC backend transport for Messaging. - - A simple messaging service that implements chat rooms and - profile posts. - This messaging service showcases the features that API clients - generated by gapic-generators implement. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'localhost:7469', - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'localhost:7469', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_room(self) -> Callable[ - [messaging.CreateRoomRequest], - messaging.Room]: - r"""Return a callable for the create room method over gRPC. - - Creates a room. - - Returns: - Callable[[~.CreateRoomRequest], - ~.Room]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_room' not in self._stubs: - self._stubs['create_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/CreateRoom', - request_serializer=messaging.CreateRoomRequest.serialize, - response_deserializer=messaging.Room.deserialize, - ) - return self._stubs['create_room'] - - @property - def get_room(self) -> Callable[ - [messaging.GetRoomRequest], - messaging.Room]: - r"""Return a callable for the get room method over gRPC. - - Retrieves the Room with the given resource name. - - Returns: - Callable[[~.GetRoomRequest], - ~.Room]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_room' not in self._stubs: - self._stubs['get_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/GetRoom', - request_serializer=messaging.GetRoomRequest.serialize, - response_deserializer=messaging.Room.deserialize, - ) - return self._stubs['get_room'] - - @property - def update_room(self) -> Callable[ - [messaging.UpdateRoomRequest], - messaging.Room]: - r"""Return a callable for the update room method over gRPC. - - Updates a room. - - Returns: - Callable[[~.UpdateRoomRequest], - ~.Room]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_room' not in self._stubs: - self._stubs['update_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/UpdateRoom', - request_serializer=messaging.UpdateRoomRequest.serialize, - response_deserializer=messaging.Room.deserialize, - ) - return self._stubs['update_room'] - - @property - def delete_room(self) -> Callable[ - [messaging.DeleteRoomRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete room method over gRPC. - - Deletes a room and all of its blurbs. - - Returns: - Callable[[~.DeleteRoomRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_room' not in self._stubs: - self._stubs['delete_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/DeleteRoom', - request_serializer=messaging.DeleteRoomRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_room'] - - @property - def list_rooms(self) -> Callable[ - [messaging.ListRoomsRequest], - messaging.ListRoomsResponse]: - r"""Return a callable for the list rooms method over gRPC. - - Lists all chat rooms. - - Returns: - Callable[[~.ListRoomsRequest], - ~.ListRoomsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_rooms' not in self._stubs: - self._stubs['list_rooms'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/ListRooms', - request_serializer=messaging.ListRoomsRequest.serialize, - response_deserializer=messaging.ListRoomsResponse.deserialize, - ) - return self._stubs['list_rooms'] - - @property - def create_blurb(self) -> Callable[ - [messaging.CreateBlurbRequest], - messaging.Blurb]: - r"""Return a callable for the create blurb method over gRPC. - - Creates a blurb. If the parent is a room, the blurb - is understood to be a message in that room. If the - parent is a profile, the blurb is understood to be a - post on the profile. - - Returns: - Callable[[~.CreateBlurbRequest], - ~.Blurb]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_blurb' not in self._stubs: - self._stubs['create_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/CreateBlurb', - request_serializer=messaging.CreateBlurbRequest.serialize, - response_deserializer=messaging.Blurb.deserialize, - ) - return self._stubs['create_blurb'] - - @property - def get_blurb(self) -> Callable[ - [messaging.GetBlurbRequest], - messaging.Blurb]: - r"""Return a callable for the get blurb method over gRPC. - - Retrieves the Blurb with the given resource name. - - Returns: - Callable[[~.GetBlurbRequest], - ~.Blurb]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_blurb' not in self._stubs: - self._stubs['get_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/GetBlurb', - request_serializer=messaging.GetBlurbRequest.serialize, - response_deserializer=messaging.Blurb.deserialize, - ) - return self._stubs['get_blurb'] - - @property - def update_blurb(self) -> Callable[ - [messaging.UpdateBlurbRequest], - messaging.Blurb]: - r"""Return a callable for the update blurb method over gRPC. - - Updates a blurb. - - Returns: - Callable[[~.UpdateBlurbRequest], - ~.Blurb]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_blurb' not in self._stubs: - self._stubs['update_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/UpdateBlurb', - request_serializer=messaging.UpdateBlurbRequest.serialize, - response_deserializer=messaging.Blurb.deserialize, - ) - return self._stubs['update_blurb'] - - @property - def delete_blurb(self) -> Callable[ - [messaging.DeleteBlurbRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete blurb method over gRPC. - - Deletes a blurb. - - Returns: - Callable[[~.DeleteBlurbRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_blurb' not in self._stubs: - self._stubs['delete_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/DeleteBlurb', - request_serializer=messaging.DeleteBlurbRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_blurb'] - - @property - def list_blurbs(self) -> Callable[ - [messaging.ListBlurbsRequest], - messaging.ListBlurbsResponse]: - r"""Return a callable for the list blurbs method over gRPC. - - Lists blurbs for a specific chat room or user profile - depending on the parent resource name. - - Returns: - Callable[[~.ListBlurbsRequest], - ~.ListBlurbsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_blurbs' not in self._stubs: - self._stubs['list_blurbs'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/ListBlurbs', - request_serializer=messaging.ListBlurbsRequest.serialize, - response_deserializer=messaging.ListBlurbsResponse.deserialize, - ) - return self._stubs['list_blurbs'] - - @property - def search_blurbs(self) -> Callable[ - [messaging.SearchBlurbsRequest], - operations_pb2.Operation]: - r"""Return a callable for the search blurbs method over gRPC. - - This method searches through all blurbs across all - rooms and profiles for blurbs containing to words found - in the query. Only posts that contain an exact match of - a queried word will be returned. - - Returns: - Callable[[~.SearchBlurbsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_blurbs' not in self._stubs: - self._stubs['search_blurbs'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/SearchBlurbs', - request_serializer=messaging.SearchBlurbsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['search_blurbs'] - - @property - def stream_blurbs(self) -> Callable[ - [messaging.StreamBlurbsRequest], - messaging.StreamBlurbsResponse]: - r"""Return a callable for the stream blurbs method over gRPC. - - This returns a stream that emits the blurbs that are - created for a particular chat room or user profile. - - Returns: - Callable[[~.StreamBlurbsRequest], - ~.StreamBlurbsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stream_blurbs' not in self._stubs: - self._stubs['stream_blurbs'] = self._logged_channel.unary_stream( - '/google.showcase.v1beta1.Messaging/StreamBlurbs', - request_serializer=messaging.StreamBlurbsRequest.serialize, - response_deserializer=messaging.StreamBlurbsResponse.deserialize, - ) - return self._stubs['stream_blurbs'] - - @property - def send_blurbs(self) -> Callable[ - [messaging.CreateBlurbRequest], - messaging.SendBlurbsResponse]: - r"""Return a callable for the send blurbs method over gRPC. - - This is a stream to create multiple blurbs. If an - invalid blurb is requested to be created, the stream - will close with an error. - - Returns: - Callable[[~.CreateBlurbRequest], - ~.SendBlurbsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'send_blurbs' not in self._stubs: - self._stubs['send_blurbs'] = self._logged_channel.stream_unary( - '/google.showcase.v1beta1.Messaging/SendBlurbs', - request_serializer=messaging.CreateBlurbRequest.serialize, - response_deserializer=messaging.SendBlurbsResponse.deserialize, - ) - return self._stubs['send_blurbs'] - - @property - def connect(self) -> Callable[ - [messaging.ConnectRequest], - messaging.StreamBlurbsResponse]: - r"""Return a callable for the connect method over gRPC. - - This method starts a bidirectional stream that - receives all blurbs that are being created after the - stream has started and sends requests to create blurbs. - If an invalid blurb is requested to be created, the - stream will close with an error. - - Returns: - Callable[[~.ConnectRequest], - ~.StreamBlurbsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'connect' not in self._stubs: - self._stubs['connect'] = self._logged_channel.stream_stream( - '/google.showcase.v1beta1.Messaging/Connect', - request_serializer=messaging.ConnectRequest.serialize, - response_deserializer=messaging.StreamBlurbsResponse.deserialize, - ) - return self._stubs['connect'] - - def close(self): - self._logged_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'MessagingGrpcTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py deleted file mode 100644 index 0011029fc37e..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/grpc_asyncio.py +++ /dev/null @@ -1,1108 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.showcase_v1beta1.types import messaging -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import MessagingTransport, DEFAULT_CLIENT_INFO -from .grpc import MessagingGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class MessagingGrpcAsyncIOTransport(MessagingTransport): - """gRPC AsyncIO backend transport for Messaging. - - A simple messaging service that implements chat rooms and - profile posts. - This messaging service showcases the features that API clients - generated by gapic-generators implement. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call 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 = 'localhost:7469', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'localhost:7469', - 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: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_room(self) -> Callable[ - [messaging.CreateRoomRequest], - Awaitable[messaging.Room]]: - r"""Return a callable for the create room method over gRPC. - - Creates a room. - - Returns: - Callable[[~.CreateRoomRequest], - Awaitable[~.Room]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_room' not in self._stubs: - self._stubs['create_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/CreateRoom', - request_serializer=messaging.CreateRoomRequest.serialize, - response_deserializer=messaging.Room.deserialize, - ) - return self._stubs['create_room'] - - @property - def get_room(self) -> Callable[ - [messaging.GetRoomRequest], - Awaitable[messaging.Room]]: - r"""Return a callable for the get room method over gRPC. - - Retrieves the Room with the given resource name. - - Returns: - Callable[[~.GetRoomRequest], - Awaitable[~.Room]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_room' not in self._stubs: - self._stubs['get_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/GetRoom', - request_serializer=messaging.GetRoomRequest.serialize, - response_deserializer=messaging.Room.deserialize, - ) - return self._stubs['get_room'] - - @property - def update_room(self) -> Callable[ - [messaging.UpdateRoomRequest], - Awaitable[messaging.Room]]: - r"""Return a callable for the update room method over gRPC. - - Updates a room. - - Returns: - Callable[[~.UpdateRoomRequest], - Awaitable[~.Room]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_room' not in self._stubs: - self._stubs['update_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/UpdateRoom', - request_serializer=messaging.UpdateRoomRequest.serialize, - response_deserializer=messaging.Room.deserialize, - ) - return self._stubs['update_room'] - - @property - def delete_room(self) -> Callable[ - [messaging.DeleteRoomRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete room method over gRPC. - - Deletes a room and all of its blurbs. - - Returns: - Callable[[~.DeleteRoomRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_room' not in self._stubs: - self._stubs['delete_room'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/DeleteRoom', - request_serializer=messaging.DeleteRoomRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_room'] - - @property - def list_rooms(self) -> Callable[ - [messaging.ListRoomsRequest], - Awaitable[messaging.ListRoomsResponse]]: - r"""Return a callable for the list rooms method over gRPC. - - Lists all chat rooms. - - Returns: - Callable[[~.ListRoomsRequest], - Awaitable[~.ListRoomsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_rooms' not in self._stubs: - self._stubs['list_rooms'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/ListRooms', - request_serializer=messaging.ListRoomsRequest.serialize, - response_deserializer=messaging.ListRoomsResponse.deserialize, - ) - return self._stubs['list_rooms'] - - @property - def create_blurb(self) -> Callable[ - [messaging.CreateBlurbRequest], - Awaitable[messaging.Blurb]]: - r"""Return a callable for the create blurb method over gRPC. - - Creates a blurb. If the parent is a room, the blurb - is understood to be a message in that room. If the - parent is a profile, the blurb is understood to be a - post on the profile. - - Returns: - Callable[[~.CreateBlurbRequest], - Awaitable[~.Blurb]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_blurb' not in self._stubs: - self._stubs['create_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/CreateBlurb', - request_serializer=messaging.CreateBlurbRequest.serialize, - response_deserializer=messaging.Blurb.deserialize, - ) - return self._stubs['create_blurb'] - - @property - def get_blurb(self) -> Callable[ - [messaging.GetBlurbRequest], - Awaitable[messaging.Blurb]]: - r"""Return a callable for the get blurb method over gRPC. - - Retrieves the Blurb with the given resource name. - - Returns: - Callable[[~.GetBlurbRequest], - Awaitable[~.Blurb]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_blurb' not in self._stubs: - self._stubs['get_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/GetBlurb', - request_serializer=messaging.GetBlurbRequest.serialize, - response_deserializer=messaging.Blurb.deserialize, - ) - return self._stubs['get_blurb'] - - @property - def update_blurb(self) -> Callable[ - [messaging.UpdateBlurbRequest], - Awaitable[messaging.Blurb]]: - r"""Return a callable for the update blurb method over gRPC. - - Updates a blurb. - - Returns: - Callable[[~.UpdateBlurbRequest], - Awaitable[~.Blurb]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_blurb' not in self._stubs: - self._stubs['update_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/UpdateBlurb', - request_serializer=messaging.UpdateBlurbRequest.serialize, - response_deserializer=messaging.Blurb.deserialize, - ) - return self._stubs['update_blurb'] - - @property - def delete_blurb(self) -> Callable[ - [messaging.DeleteBlurbRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete blurb method over gRPC. - - Deletes a blurb. - - Returns: - Callable[[~.DeleteBlurbRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_blurb' not in self._stubs: - self._stubs['delete_blurb'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/DeleteBlurb', - request_serializer=messaging.DeleteBlurbRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_blurb'] - - @property - def list_blurbs(self) -> Callable[ - [messaging.ListBlurbsRequest], - Awaitable[messaging.ListBlurbsResponse]]: - r"""Return a callable for the list blurbs method over gRPC. - - Lists blurbs for a specific chat room or user profile - depending on the parent resource name. - - Returns: - Callable[[~.ListBlurbsRequest], - Awaitable[~.ListBlurbsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_blurbs' not in self._stubs: - self._stubs['list_blurbs'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/ListBlurbs', - request_serializer=messaging.ListBlurbsRequest.serialize, - response_deserializer=messaging.ListBlurbsResponse.deserialize, - ) - return self._stubs['list_blurbs'] - - @property - def search_blurbs(self) -> Callable[ - [messaging.SearchBlurbsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the search blurbs method over gRPC. - - This method searches through all blurbs across all - rooms and profiles for blurbs containing to words found - in the query. Only posts that contain an exact match of - a queried word will be returned. - - Returns: - Callable[[~.SearchBlurbsRequest], - 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 'search_blurbs' not in self._stubs: - self._stubs['search_blurbs'] = self._logged_channel.unary_unary( - '/google.showcase.v1beta1.Messaging/SearchBlurbs', - request_serializer=messaging.SearchBlurbsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['search_blurbs'] - - @property - def stream_blurbs(self) -> Callable[ - [messaging.StreamBlurbsRequest], - Awaitable[messaging.StreamBlurbsResponse]]: - r"""Return a callable for the stream blurbs method over gRPC. - - This returns a stream that emits the blurbs that are - created for a particular chat room or user profile. - - Returns: - Callable[[~.StreamBlurbsRequest], - Awaitable[~.StreamBlurbsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stream_blurbs' not in self._stubs: - self._stubs['stream_blurbs'] = self._logged_channel.unary_stream( - '/google.showcase.v1beta1.Messaging/StreamBlurbs', - request_serializer=messaging.StreamBlurbsRequest.serialize, - response_deserializer=messaging.StreamBlurbsResponse.deserialize, - ) - return self._stubs['stream_blurbs'] - - @property - def send_blurbs(self) -> Callable[ - [messaging.CreateBlurbRequest], - Awaitable[messaging.SendBlurbsResponse]]: - r"""Return a callable for the send blurbs method over gRPC. - - This is a stream to create multiple blurbs. If an - invalid blurb is requested to be created, the stream - will close with an error. - - Returns: - Callable[[~.CreateBlurbRequest], - Awaitable[~.SendBlurbsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'send_blurbs' not in self._stubs: - self._stubs['send_blurbs'] = self._logged_channel.stream_unary( - '/google.showcase.v1beta1.Messaging/SendBlurbs', - request_serializer=messaging.CreateBlurbRequest.serialize, - response_deserializer=messaging.SendBlurbsResponse.deserialize, - ) - return self._stubs['send_blurbs'] - - @property - def connect(self) -> Callable[ - [messaging.ConnectRequest], - Awaitable[messaging.StreamBlurbsResponse]]: - r"""Return a callable for the connect method over gRPC. - - This method starts a bidirectional stream that - receives all blurbs that are being created after the - stream has started and sends requests to create blurbs. - If an invalid blurb is requested to be created, the - stream will close with an error. - - Returns: - Callable[[~.ConnectRequest], - Awaitable[~.StreamBlurbsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'connect' not in self._stubs: - self._stubs['connect'] = self._logged_channel.stream_stream( - '/google.showcase.v1beta1.Messaging/Connect', - request_serializer=messaging.ConnectRequest.serialize, - response_deserializer=messaging.StreamBlurbsResponse.deserialize, - ) - return self._stubs['connect'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_room: self._wrap_method( - self.create_room, - default_timeout=None, - client_info=client_info, - ), - self.get_room: self._wrap_method( - self.get_room, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.update_room: self._wrap_method( - self.update_room, - default_timeout=None, - client_info=client_info, - ), - self.delete_room: self._wrap_method( - self.delete_room, - default_timeout=None, - client_info=client_info, - ), - self.list_rooms: self._wrap_method( - self.list_rooms, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.create_blurb: self._wrap_method( - self.create_blurb, - default_timeout=None, - client_info=client_info, - ), - self.get_blurb: self._wrap_method( - self.get_blurb, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.update_blurb: self._wrap_method( - self.update_blurb, - default_timeout=None, - client_info=client_info, - ), - self.delete_blurb: self._wrap_method( - self.delete_blurb, - default_timeout=None, - client_info=client_info, - ), - self.list_blurbs: self._wrap_method( - self.list_blurbs, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.search_blurbs: self._wrap_method( - self.search_blurbs, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.stream_blurbs: self._wrap_method( - self.stream_blurbs, - default_timeout=None, - client_info=client_info, - ), - self.send_blurbs: self._wrap_method( - self.send_blurbs, - default_timeout=None, - client_info=client_info, - ), - self.connect: self._wrap_method( - self.connect, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=3.0, - multiplier=2, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=10.0, - ), - default_timeout=10.0, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - 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.get_iam_policy: self._wrap_method( - self.get_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.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_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.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'MessagingGrpcAsyncIOTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py deleted file mode 100644 index 47c17322d876..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest.py +++ /dev/null @@ -1,3559 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # 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.showcase_v1beta1 import _compat as rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -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.showcase_v1beta1.types import messaging -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseMessagingRestTransport -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 - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class MessagingRestInterceptor: - """Interceptor for Messaging. - - 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 MessagingRestTransport. - - .. code-block:: python - class MyCustomMessagingInterceptor(MessagingRestInterceptor): - def pre_create_blurb(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_blurb(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_room(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_room(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_blurb(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_room(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_blurb(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_blurb(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_room(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_room(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_blurbs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_blurbs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_rooms(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_rooms(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_blurbs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_blurbs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stream_blurbs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stream_blurbs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_blurb(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_blurb(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_room(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_room(self, response): - logging.log(f"Received response: {response}") - return response - - transport = MessagingRestTransport(interceptor=MyCustomMessagingInterceptor()) - client = MessagingClient(transport=transport) - - - """ - def pre_create_blurb(self, request: messaging.CreateBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.CreateBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_blurb - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_create_blurb(self, response: messaging.Blurb) -> messaging.Blurb: - """Post-rpc interceptor for create_blurb - - DEPRECATED. Please use the `post_create_blurb_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_create_blurb` interceptor runs - before the `post_create_blurb_with_metadata` interceptor. - """ - return response - - def post_create_blurb_with_metadata(self, response: messaging.Blurb, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Blurb, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_blurb - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_create_blurb_with_metadata` - interceptor in new development instead of the `post_create_blurb` interceptor. - When both interceptors are used, this `post_create_blurb_with_metadata` interceptor runs after the - `post_create_blurb` interceptor. The (possibly modified) response returned by - `post_create_blurb` will be passed to - `post_create_blurb_with_metadata`. - """ - return response, metadata - - def pre_create_room(self, request: messaging.CreateRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.CreateRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_room - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_create_room(self, response: messaging.Room) -> messaging.Room: - """Post-rpc interceptor for create_room - - DEPRECATED. Please use the `post_create_room_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_create_room` interceptor runs - before the `post_create_room_with_metadata` interceptor. - """ - return response - - def post_create_room_with_metadata(self, response: messaging.Room, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Room, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_room - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_create_room_with_metadata` - interceptor in new development instead of the `post_create_room` interceptor. - When both interceptors are used, this `post_create_room_with_metadata` interceptor runs after the - `post_create_room` interceptor. The (possibly modified) response returned by - `post_create_room` will be passed to - `post_create_room_with_metadata`. - """ - return response, metadata - - def pre_delete_blurb(self, request: messaging.DeleteBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.DeleteBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_blurb - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def pre_delete_room(self, request: messaging.DeleteRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.DeleteRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_room - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def pre_get_blurb(self, request: messaging.GetBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.GetBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_blurb - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_get_blurb(self, response: messaging.Blurb) -> messaging.Blurb: - """Post-rpc interceptor for get_blurb - - DEPRECATED. Please use the `post_get_blurb_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_get_blurb` interceptor runs - before the `post_get_blurb_with_metadata` interceptor. - """ - return response - - def post_get_blurb_with_metadata(self, response: messaging.Blurb, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Blurb, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_blurb - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_get_blurb_with_metadata` - interceptor in new development instead of the `post_get_blurb` interceptor. - When both interceptors are used, this `post_get_blurb_with_metadata` interceptor runs after the - `post_get_blurb` interceptor. The (possibly modified) response returned by - `post_get_blurb` will be passed to - `post_get_blurb_with_metadata`. - """ - return response, metadata - - def pre_get_room(self, request: messaging.GetRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.GetRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_room - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_get_room(self, response: messaging.Room) -> messaging.Room: - """Post-rpc interceptor for get_room - - DEPRECATED. Please use the `post_get_room_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_get_room` interceptor runs - before the `post_get_room_with_metadata` interceptor. - """ - return response - - def post_get_room_with_metadata(self, response: messaging.Room, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Room, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_room - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_get_room_with_metadata` - interceptor in new development instead of the `post_get_room` interceptor. - When both interceptors are used, this `post_get_room_with_metadata` interceptor runs after the - `post_get_room` interceptor. The (possibly modified) response returned by - `post_get_room` will be passed to - `post_get_room_with_metadata`. - """ - return response, metadata - - def pre_list_blurbs(self, request: messaging.ListBlurbsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListBlurbsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_blurbs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_list_blurbs(self, response: messaging.ListBlurbsResponse) -> messaging.ListBlurbsResponse: - """Post-rpc interceptor for list_blurbs - - DEPRECATED. Please use the `post_list_blurbs_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_list_blurbs` interceptor runs - before the `post_list_blurbs_with_metadata` interceptor. - """ - return response - - def post_list_blurbs_with_metadata(self, response: messaging.ListBlurbsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListBlurbsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_blurbs - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_list_blurbs_with_metadata` - interceptor in new development instead of the `post_list_blurbs` interceptor. - When both interceptors are used, this `post_list_blurbs_with_metadata` interceptor runs after the - `post_list_blurbs` interceptor. The (possibly modified) response returned by - `post_list_blurbs` will be passed to - `post_list_blurbs_with_metadata`. - """ - return response, metadata - - def pre_list_rooms(self, request: messaging.ListRoomsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListRoomsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_rooms - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_list_rooms(self, response: messaging.ListRoomsResponse) -> messaging.ListRoomsResponse: - """Post-rpc interceptor for list_rooms - - DEPRECATED. Please use the `post_list_rooms_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_list_rooms` interceptor runs - before the `post_list_rooms_with_metadata` interceptor. - """ - return response - - def post_list_rooms_with_metadata(self, response: messaging.ListRoomsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.ListRoomsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_rooms - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_list_rooms_with_metadata` - interceptor in new development instead of the `post_list_rooms` interceptor. - When both interceptors are used, this `post_list_rooms_with_metadata` interceptor runs after the - `post_list_rooms` interceptor. The (possibly modified) response returned by - `post_list_rooms` will be passed to - `post_list_rooms_with_metadata`. - """ - return response, metadata - - def pre_search_blurbs(self, request: messaging.SearchBlurbsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.SearchBlurbsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for search_blurbs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_search_blurbs(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for search_blurbs - - DEPRECATED. Please use the `post_search_blurbs_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_search_blurbs` interceptor runs - before the `post_search_blurbs_with_metadata` interceptor. - """ - return response - - def post_search_blurbs_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for search_blurbs - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_search_blurbs_with_metadata` - interceptor in new development instead of the `post_search_blurbs` interceptor. - When both interceptors are used, this `post_search_blurbs_with_metadata` interceptor runs after the - `post_search_blurbs` interceptor. The (possibly modified) response returned by - `post_search_blurbs` will be passed to - `post_search_blurbs_with_metadata`. - """ - return response, metadata - - def pre_stream_blurbs(self, request: messaging.StreamBlurbsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.StreamBlurbsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for stream_blurbs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_stream_blurbs(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for stream_blurbs - - DEPRECATED. Please use the `post_stream_blurbs_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_stream_blurbs` interceptor runs - before the `post_stream_blurbs_with_metadata` interceptor. - """ - return response - - def post_stream_blurbs_with_metadata(self, response: rest_streaming.ResponseIterator, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for stream_blurbs - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_stream_blurbs_with_metadata` - interceptor in new development instead of the `post_stream_blurbs` interceptor. - When both interceptors are used, this `post_stream_blurbs_with_metadata` interceptor runs after the - `post_stream_blurbs` interceptor. The (possibly modified) response returned by - `post_stream_blurbs` will be passed to - `post_stream_blurbs_with_metadata`. - """ - return response, metadata - - def pre_update_blurb(self, request: messaging.UpdateBlurbRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.UpdateBlurbRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_blurb - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_update_blurb(self, response: messaging.Blurb) -> messaging.Blurb: - """Post-rpc interceptor for update_blurb - - DEPRECATED. Please use the `post_update_blurb_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_update_blurb` interceptor runs - before the `post_update_blurb_with_metadata` interceptor. - """ - return response - - def post_update_blurb_with_metadata(self, response: messaging.Blurb, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Blurb, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_blurb - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_update_blurb_with_metadata` - interceptor in new development instead of the `post_update_blurb` interceptor. - When both interceptors are used, this `post_update_blurb_with_metadata` interceptor runs after the - `post_update_blurb` interceptor. The (possibly modified) response returned by - `post_update_blurb` will be passed to - `post_update_blurb_with_metadata`. - """ - return response, metadata - - def pre_update_room(self, request: messaging.UpdateRoomRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.UpdateRoomRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_room - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging server. - """ - return request, metadata - - def post_update_room(self, response: messaging.Room) -> messaging.Room: - """Post-rpc interceptor for update_room - - DEPRECATED. Please use the `post_update_room_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Messaging server but before - it is returned to user code. This `post_update_room` interceptor runs - before the `post_update_room_with_metadata` interceptor. - """ - return response - - def post_update_room_with_metadata(self, response: messaging.Room, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[messaging.Room, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_room - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Messaging server but before it is returned to user code. - - We recommend only using this `post_update_room_with_metadata` - interceptor in new development instead of the `post_update_room` interceptor. - When both interceptors are used, this `post_update_room_with_metadata` interceptor runs after the - `post_update_room` interceptor. The (possibly modified) response returned by - `post_update_room` will be passed to - `post_update_room_with_metadata`. - """ - return response, metadata - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Messaging 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 Messaging server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class MessagingRestStub: - _session: AuthorizedSession - _host: str - _interceptor: MessagingRestInterceptor - - -class MessagingRestTransport(_BaseMessagingRestTransport): - """REST backend synchronous transport for Messaging. - - A simple messaging service that implements chat rooms and - profile posts. - This messaging service showcases the features that API clients - generated by gapic-generators implement. - - This 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 = 'localhost:7469', - 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[MessagingRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'localhost:7469'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[MessagingRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. - """ - # 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 MessagingRestInterceptor() - 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.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta1/operations', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=operations/**}', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta1/{name=operations/**}', - }, - ], - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta1/{name=operations/**}:cancel', - }, - ], - } - - 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="v1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _Connect(_BaseMessagingRestTransport._BaseConnect, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.Connect") - - def __call__(self, - request: messaging.ConnectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method Connect is not available over REST transport" - ) - class _CreateBlurb(_BaseMessagingRestTransport._BaseCreateBlurb, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.CreateBlurb") - - @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: messaging.CreateBlurbRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.Blurb: - r"""Call the create blurb method over HTTP. - - Args: - request (~.messaging.CreateBlurbRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\CreateBlurb - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - - http_options = _BaseMessagingRestTransport._BaseCreateBlurb._get_http_options() - request, metadata = self._interceptor.pre_create_blurb(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseCreateBlurb, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.CreateBlurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "CreateBlurb", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._CreateBlurb._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 = messaging.Blurb() - pb_resp = messaging.Blurb.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_blurb(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_blurb_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.Blurb.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.create_blurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "CreateBlurb", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateRoom(_BaseMessagingRestTransport._BaseCreateRoom, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.CreateRoom") - - @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: messaging.CreateRoomRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.Room: - r"""Call the create room method over HTTP. - - Args: - request (~.messaging.CreateRoomRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\CreateRoom - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.Room: - A chat room. - """ - - http_options = _BaseMessagingRestTransport._BaseCreateRoom._get_http_options() - request, metadata = self._interceptor.pre_create_room(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseCreateRoom, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.CreateRoom", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "CreateRoom", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._CreateRoom._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 = messaging.Room() - pb_resp = messaging.Room.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_room(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_room_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.Room.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.create_room", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "CreateRoom", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteBlurb(_BaseMessagingRestTransport._BaseDeleteBlurb, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.DeleteBlurb") - - @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: messaging.DeleteBlurbRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete blurb method over HTTP. - - Args: - request (~.messaging.DeleteBlurbRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\DeleteBlurb - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseMessagingRestTransport._BaseDeleteBlurb._get_http_options() - request, metadata = self._interceptor.pre_delete_blurb(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseDeleteBlurb, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.DeleteBlurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "DeleteBlurb", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._DeleteBlurb._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteRoom(_BaseMessagingRestTransport._BaseDeleteRoom, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.DeleteRoom") - - @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: messaging.DeleteRoomRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete room method over HTTP. - - Args: - request (~.messaging.DeleteRoomRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\DeleteRoom - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseMessagingRestTransport._BaseDeleteRoom._get_http_options() - request, metadata = self._interceptor.pre_delete_room(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseDeleteRoom, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.DeleteRoom", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "DeleteRoom", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._DeleteRoom._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetBlurb(_BaseMessagingRestTransport._BaseGetBlurb, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.GetBlurb") - - @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: messaging.GetBlurbRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.Blurb: - r"""Call the get blurb method over HTTP. - - Args: - request (~.messaging.GetBlurbRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\GetBlurb - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - - http_options = _BaseMessagingRestTransport._BaseGetBlurb._get_http_options() - request, metadata = self._interceptor.pre_get_blurb(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseGetBlurb, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.GetBlurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetBlurb", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._GetBlurb._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 = messaging.Blurb() - pb_resp = messaging.Blurb.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_blurb(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_blurb_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.Blurb.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.get_blurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetBlurb", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetRoom(_BaseMessagingRestTransport._BaseGetRoom, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.GetRoom") - - @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: messaging.GetRoomRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.Room: - r"""Call the get room method over HTTP. - - Args: - request (~.messaging.GetRoomRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\GetRoom - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.Room: - A chat room. - """ - - http_options = _BaseMessagingRestTransport._BaseGetRoom._get_http_options() - request, metadata = self._interceptor.pre_get_room(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseGetRoom, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.GetRoom", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetRoom", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._GetRoom._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 = messaging.Room() - pb_resp = messaging.Room.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_room(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_room_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.Room.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.get_room", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetRoom", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListBlurbs(_BaseMessagingRestTransport._BaseListBlurbs, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.ListBlurbs") - - @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: messaging.ListBlurbsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.ListBlurbsResponse: - r"""Call the list blurbs method over HTTP. - - Args: - request (~.messaging.ListBlurbsRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\ListBlurbs - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.ListBlurbsResponse: - The response message for the - google.showcase.v1beta1.Messaging\ListBlurbs - method. - - """ - - http_options = _BaseMessagingRestTransport._BaseListBlurbs._get_http_options() - request, metadata = self._interceptor.pre_list_blurbs(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseListBlurbs, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.ListBlurbs", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListBlurbs", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._ListBlurbs._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 = messaging.ListBlurbsResponse() - pb_resp = messaging.ListBlurbsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_blurbs(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_blurbs_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.ListBlurbsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.list_blurbs", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListBlurbs", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListRooms(_BaseMessagingRestTransport._BaseListRooms, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.ListRooms") - - @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: messaging.ListRoomsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.ListRoomsResponse: - r"""Call the list rooms method over HTTP. - - Args: - request (~.messaging.ListRoomsRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\ListRooms - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.ListRoomsResponse: - The response message for the - google.showcase.v1beta1.Messaging\ListRooms - method. - - """ - - http_options = _BaseMessagingRestTransport._BaseListRooms._get_http_options() - request, metadata = self._interceptor.pre_list_rooms(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseListRooms, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.ListRooms", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListRooms", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._ListRooms._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 = messaging.ListRoomsResponse() - pb_resp = messaging.ListRoomsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_rooms(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_rooms_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.ListRoomsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.list_rooms", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListRooms", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SearchBlurbs(_BaseMessagingRestTransport._BaseSearchBlurbs, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.SearchBlurbs") - - @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: messaging.SearchBlurbsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the search blurbs method over HTTP. - - Args: - request (~.messaging.SearchBlurbsRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\SearchBlurbs - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseMessagingRestTransport._BaseSearchBlurbs._get_http_options() - request, metadata = self._interceptor.pre_search_blurbs(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseSearchBlurbs, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.SearchBlurbs", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "SearchBlurbs", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._SearchBlurbs._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_search_blurbs(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_search_blurbs_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.search_blurbs", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "SearchBlurbs", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SendBlurbs(_BaseMessagingRestTransport._BaseSendBlurbs, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.SendBlurbs") - - def __call__(self, - request: messaging.CreateBlurbRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.SendBlurbsResponse: - raise NotImplementedError( - "Method SendBlurbs is not available over REST transport" - ) - class _StreamBlurbs(_BaseMessagingRestTransport._BaseStreamBlurbs, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.StreamBlurbs") - - @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, - stream=True, - ) - return response - - def __call__(self, - request: messaging.StreamBlurbsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the stream blurbs method over HTTP. - - Args: - request (~.messaging.StreamBlurbsRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.StreamBlurbsResponse: - The response message for the - google.showcase.v1beta1.Messaging\StreamBlurbs - method. - - """ - - http_options = _BaseMessagingRestTransport._BaseStreamBlurbs._get_http_options() - request, metadata = self._interceptor.pre_stream_blurbs(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseStreamBlurbs, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.StreamBlurbs", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "StreamBlurbs", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._StreamBlurbs._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 = rest_streaming.ResponseIterator(response, messaging.StreamBlurbsResponse) - - resp = self._interceptor.post_stream_blurbs(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_stream_blurbs_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - http_response = { - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.stream_blurbs", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "StreamBlurbs", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateBlurb(_BaseMessagingRestTransport._BaseUpdateBlurb, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.UpdateBlurb") - - @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: messaging.UpdateBlurbRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.Blurb: - r"""Call the update blurb method over HTTP. - - Args: - request (~.messaging.UpdateBlurbRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\UpdateBlurb - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.Blurb: - This protocol buffer message - represents a blurb sent to a chat room - or posted on a user profile. - - """ - - http_options = _BaseMessagingRestTransport._BaseUpdateBlurb._get_http_options() - request, metadata = self._interceptor.pre_update_blurb(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseUpdateBlurb, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.UpdateBlurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "UpdateBlurb", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._UpdateBlurb._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 = messaging.Blurb() - pb_resp = messaging.Blurb.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_blurb(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_blurb_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.Blurb.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.update_blurb", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "UpdateBlurb", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateRoom(_BaseMessagingRestTransport._BaseUpdateRoom, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.UpdateRoom") - - @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: messaging.UpdateRoomRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> messaging.Room: - r"""Call the update room method over HTTP. - - Args: - request (~.messaging.UpdateRoomRequest): - The request object. The request message for the - google.showcase.v1beta1.Messaging\UpdateRoom - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.messaging.Room: - A chat room. - """ - - http_options = _BaseMessagingRestTransport._BaseUpdateRoom._get_http_options() - request, metadata = self._interceptor.pre_update_room(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseUpdateRoom, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.UpdateRoom", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "UpdateRoom", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._UpdateRoom._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 = messaging.Room() - pb_resp = messaging.Room.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_room(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_room_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = messaging.Room.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingClient.update_room", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "UpdateRoom", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def connect(self) -> Callable[ - [messaging.ConnectRequest], - messaging.StreamBlurbsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Connect(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_blurb(self) -> Callable[ - [messaging.CreateBlurbRequest], - messaging.Blurb]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateBlurb(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_room(self) -> Callable[ - [messaging.CreateRoomRequest], - messaging.Room]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateRoom(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_blurb(self) -> Callable[ - [messaging.DeleteBlurbRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteBlurb(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_room(self) -> Callable[ - [messaging.DeleteRoomRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteRoom(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_blurb(self) -> Callable[ - [messaging.GetBlurbRequest], - messaging.Blurb]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetBlurb(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_room(self) -> Callable[ - [messaging.GetRoomRequest], - messaging.Room]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetRoom(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_blurbs(self) -> Callable[ - [messaging.ListBlurbsRequest], - messaging.ListBlurbsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListBlurbs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_rooms(self) -> Callable[ - [messaging.ListRoomsRequest], - messaging.ListRoomsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListRooms(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_blurbs(self) -> Callable[ - [messaging.SearchBlurbsRequest], - 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._SearchBlurbs(self._session, self._host, self._interceptor) # type: ignore - - @property - def send_blurbs(self) -> Callable[ - [messaging.CreateBlurbRequest], - messaging.SendBlurbsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SendBlurbs(self._session, self._host, self._interceptor) # type: ignore - - @property - def stream_blurbs(self) -> Callable[ - [messaging.StreamBlurbsRequest], - messaging.StreamBlurbsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StreamBlurbs(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_blurb(self) -> Callable[ - [messaging.UpdateBlurbRequest], - messaging.Blurb]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateBlurb(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_room(self) -> Callable[ - [messaging.UpdateRoomRequest], - messaging.Room]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateRoom(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseMessagingRestTransport._BaseListLocations, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseMessagingRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseListLocations, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.ListLocations", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListLocations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.ListLocations", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListLocations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseMessagingRestTransport._BaseGetLocation, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseMessagingRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseGetLocation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.GetLocation", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetLocation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.GetLocation", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetLocation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseMessagingRestTransport._BaseSetIamPolicy, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseMessagingRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseSetIamPolicy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.SetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "SetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseMessagingRestTransport._BaseGetIamPolicy, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseMessagingRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseGetIamPolicy, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.GetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseMessagingRestTransport._BaseTestIamPermissions, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseMessagingRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseTestIamPermissions, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.TestIamPermissions", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "TestIamPermissions", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseMessagingRestTransport._BaseListOperations, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseMessagingRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseListOperations, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.ListOperations", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.ListOperations", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseMessagingRestTransport._BaseGetOperation, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseMessagingRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseGetOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.GetOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.showcase_v1beta1.MessagingAsyncClient.GetOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseMessagingRestTransport._BaseDeleteOperation, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseMessagingRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseDeleteOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.DeleteOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._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 cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseMessagingRestTransport._BaseCancelOperation, MessagingRestStub): - def __hash__(self): - return hash("MessagingRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseMessagingRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request, body, query_params = rest_helpers.transcode_request( - http_options, - request, - required_fields_default_values=getattr( - _BaseMessagingRestTransport._BaseCancelOperation, - "__REQUIRED_FIELDS_DEFAULT_VALUES", - None, - ), - rest_numeric_enums=False, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.showcase_v1beta1.MessagingClient.CancelOperation", - extra = { - "serviceName": "google.showcase.v1beta1.Messaging", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = MessagingRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'MessagingRestTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py deleted file mode 100644 index 13e97282bc2f..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/services/messaging/transports/rest_base.py +++ /dev/null @@ -1,524 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 MessagingTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.showcase_v1beta1.types import messaging -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseMessagingRestTransport(MessagingTransport): - """Base REST backend transport for Messaging. - - 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 = 'localhost:7469', - 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: 'localhost:7469'). - 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 _BaseConnect: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - class _BaseCreateBlurb: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=rooms/*}/blurbs', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{parent=users/*/profile}/blurbs', - 'body': '*', - }, - ] - return http_options - - class _BaseCreateRoom: - 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': '/v1beta1/rooms', - 'body': '*', - }, - ] - return http_options - - class _BaseDeleteBlurb: - 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': '/v1beta1/{name=rooms/*/blurbs/*}', - }, - { - 'method': 'delete', - 'uri': '/v1beta1/{name=users/*/profile/blurbs/*}', - }, - ] - return http_options - - class _BaseDeleteRoom: - 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': '/v1beta1/{name=rooms/*}', - }, - ] - return http_options - - class _BaseGetBlurb: - 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': '/v1beta1/{name=rooms/*/blurbs/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{name=users/*/profile/blurbs/*}', - }, - ] - return http_options - - class _BaseGetRoom: - 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': '/v1beta1/{name=rooms/*}', - }, - ] - return http_options - - class _BaseListBlurbs: - 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': '/v1beta1/{parent=rooms/*}/blurbs', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{parent=users/*/profile}/blurbs', - }, - ] - return http_options - - class _BaseListRooms: - 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': '/v1beta1/rooms', - }, - ] - return http_options - - class _BaseSearchBlurbs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=rooms/*}/blurbs:search', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{parent=users/*/profile}/blurbs:search', - }, - ] - return http_options - - class _BaseSendBlurbs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - class _BaseStreamBlurbs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{name=rooms/*}/blurbs:stream', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{name=users/*/profile}/blurbs:stream', - 'body': '*', - }, - ] - return http_options - - class _BaseUpdateBlurb: - 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': '/v1beta1/{blurb.name=rooms/*/blurbs/*}', - 'body': 'blurb', - }, - { - 'method': 'patch', - 'uri': '/v1beta1/{blurb.name=users/*/profile/blurbs/*}', - 'body': 'blurb', - }, - ] - return http_options - - class _BaseUpdateRoom: - 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': '/v1beta1/{room.name=rooms/*}', - 'body': 'room', - }, - ] - return http_options - - 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': '/v1beta1/{name=projects/*}/locations', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=projects/*/locations/*}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=sequences/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=rooms/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1beta1/{resource=sequences/*}:getIamPolicy', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{resource=users/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1beta1/{resource=sequences/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - pass - - 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': '/v1beta1/operations', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}', - }, - ] - return http_options - - pass - - 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': '/v1beta1/{name=operations/**}:cancel', - }, - ] - return http_options - - pass - - -__all__=( - '_BaseMessagingRestTransport', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py deleted file mode 100644 index 1b940c7a2478..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .echo import ( - BlockRequest, - BlockResponse, - EchoErrorDetailsRequest, - EchoErrorDetailsResponse, - EchoRequest, - EchoResponse, - ErrorWithMultipleDetails, - ErrorWithSingleDetail, - ExpandRequest, - PagedExpandLegacyMappedResponse, - PagedExpandLegacyRequest, - PagedExpandRequest, - PagedExpandResponse, - PagedExpandResponseList, - WaitMetadata, - WaitRequest, - WaitResponse, - Severity, -) -from .identity import ( - CreateUserRequest, - DeleteUserRequest, - GetUserRequest, - ListUsersRequest, - ListUsersResponse, - UpdateUserRequest, - User, -) -from .messaging import ( - Blurb, - ConnectRequest, - CreateBlurbRequest, - CreateRoomRequest, - DeleteBlurbRequest, - DeleteRoomRequest, - GetBlurbRequest, - GetRoomRequest, - ListBlurbsRequest, - ListBlurbsResponse, - ListRoomsRequest, - ListRoomsResponse, - Room, - SearchBlurbsMetadata, - SearchBlurbsRequest, - SearchBlurbsResponse, - SendBlurbsResponse, - StreamBlurbsRequest, - StreamBlurbsResponse, - UpdateBlurbRequest, - UpdateRoomRequest, -) - -__all__ = ( - 'BlockRequest', - 'BlockResponse', - 'EchoErrorDetailsRequest', - 'EchoErrorDetailsResponse', - 'EchoRequest', - 'EchoResponse', - 'ErrorWithMultipleDetails', - 'ErrorWithSingleDetail', - 'ExpandRequest', - 'PagedExpandLegacyMappedResponse', - 'PagedExpandLegacyRequest', - 'PagedExpandRequest', - 'PagedExpandResponse', - 'PagedExpandResponseList', - 'WaitMetadata', - 'WaitRequest', - 'WaitResponse', - 'Severity', - 'CreateUserRequest', - 'DeleteUserRequest', - 'GetUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - 'UpdateUserRequest', - 'User', - 'Blurb', - 'ConnectRequest', - 'CreateBlurbRequest', - 'CreateRoomRequest', - 'DeleteBlurbRequest', - 'DeleteRoomRequest', - 'GetBlurbRequest', - 'GetRoomRequest', - 'ListBlurbsRequest', - 'ListBlurbsResponse', - 'ListRoomsRequest', - 'ListRoomsResponse', - 'Room', - 'SearchBlurbsMetadata', - 'SearchBlurbsRequest', - 'SearchBlurbsResponse', - 'SendBlurbsResponse', - 'StreamBlurbsRequest', - 'StreamBlurbsResponse', - 'UpdateBlurbRequest', - 'UpdateRoomRequest', -) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py deleted file mode 100644 index 6522ce6eec90..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/echo.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -import google.protobuf.any_pb2 as any_pb2 # type: ignore -import google.protobuf.duration_pb2 as duration_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -import google.rpc.status_pb2 as status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.showcase.v1beta1', - manifest={ - 'Severity', - 'EchoRequest', - 'EchoResponse', - 'EchoErrorDetailsRequest', - 'EchoErrorDetailsResponse', - 'ErrorWithSingleDetail', - 'ErrorWithMultipleDetails', - 'ExpandRequest', - 'PagedExpandRequest', - 'PagedExpandLegacyRequest', - 'PagedExpandResponse', - 'PagedExpandResponseList', - 'PagedExpandLegacyMappedResponse', - 'WaitRequest', - 'WaitResponse', - 'WaitMetadata', - 'BlockRequest', - 'BlockResponse', - }, -) - - -class Severity(proto.Enum): - r"""A severity enum used to test enum capabilities in GAPIC - surfaces. - - Values: - UNNECESSARY (0): - No description available. - NECESSARY (1): - No description available. - URGENT (2): - No description available. - CRITICAL (3): - No description available. - """ - UNNECESSARY = 0 - NECESSARY = 1 - URGENT = 2 - CRITICAL = 3 - - -class EchoRequest(proto.Message): - r"""The request message used for the Echo, Collect and Chat - methods. If content or opt are set in this message then the - request will succeed. If status is set in this message then the - status will be returned as an error. - - 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: - content (str): - The content to be echoed by the server. - - This field is a member of `oneof`_ ``response``. - error (google.rpc.status_pb2.Status): - The error to be thrown by the server. - - This field is a member of `oneof`_ ``response``. - severity (google.showcase_v1beta1.types.Severity): - The severity to be echoed by the server. - header (str): - Optional. This field can be set to test the - routing annotation on the Echo method. - other_header (str): - Optional. This field can be set to test the - routing annotation on the Echo method. - request_id (str): - To facilitate testing of - https://google.aip.dev/client-libraries/4235 - other_request_id (str): - To facilitate testing of - https://google.aip.dev/client-libraries/4235 - - This field is a member of `oneof`_ ``_other_request_id``. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - oneof='response', - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - oneof='response', - message=status_pb2.Status, - ) - severity: 'Severity' = proto.Field( - proto.ENUM, - number=3, - enum='Severity', - ) - header: str = proto.Field( - proto.STRING, - number=4, - ) - other_header: str = proto.Field( - proto.STRING, - number=5, - ) - request_id: str = proto.Field( - proto.STRING, - number=7, - ) - other_request_id: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - - -class EchoResponse(proto.Message): - r"""The response message for the Echo methods. - - Attributes: - content (str): - The content specified in the request. - severity (google.showcase_v1beta1.types.Severity): - The severity specified in the request. - request_id (str): - The request ID specified or autopopulated in - the request. - other_request_id (str): - The other request ID specified or - autopopulated in the request. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - severity: 'Severity' = proto.Field( - proto.ENUM, - number=2, - enum='Severity', - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - other_request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class EchoErrorDetailsRequest(proto.Message): - r"""The request message used for the EchoErrorDetails method. - - Attributes: - single_detail_text (str): - Content to return in a singular ``*.error.details`` field of - type ``google.protobuf.Any`` - multi_detail_text (MutableSequence[str]): - Content to return in a repeated ``*.error.details`` field of - type ``google.protobuf.Any`` - """ - - single_detail_text: str = proto.Field( - proto.STRING, - number=1, - ) - multi_detail_text: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class EchoErrorDetailsResponse(proto.Message): - r"""The response message used for the EchoErrorDetails method. - - Attributes: - single_detail (google.showcase_v1beta1.types.EchoErrorDetailsResponse.SingleDetail): - - multiple_details (google.showcase_v1beta1.types.EchoErrorDetailsResponse.MultipleDetails): - - """ - - class SingleDetail(proto.Message): - r""" - - Attributes: - error (google.showcase_v1beta1.types.ErrorWithSingleDetail): - - """ - - error: 'ErrorWithSingleDetail' = proto.Field( - proto.MESSAGE, - number=1, - message='ErrorWithSingleDetail', - ) - - class MultipleDetails(proto.Message): - r""" - - Attributes: - error (google.showcase_v1beta1.types.ErrorWithMultipleDetails): - - """ - - error: 'ErrorWithMultipleDetails' = proto.Field( - proto.MESSAGE, - number=1, - message='ErrorWithMultipleDetails', - ) - - single_detail: SingleDetail = proto.Field( - proto.MESSAGE, - number=1, - message=SingleDetail, - ) - multiple_details: MultipleDetails = proto.Field( - proto.MESSAGE, - number=2, - message=MultipleDetails, - ) - - -class ErrorWithSingleDetail(proto.Message): - r""" - - Attributes: - details (google.protobuf.any_pb2.Any): - - """ - - details: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=1, - message=any_pb2.Any, - ) - - -class ErrorWithMultipleDetails(proto.Message): - r""" - - Attributes: - details (MutableSequence[google.protobuf.any_pb2.Any]): - - """ - - details: MutableSequence[any_pb2.Any] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=any_pb2.Any, - ) - - -class ExpandRequest(proto.Message): - r"""The request message for the Expand method. - - Attributes: - content (str): - The content that will be split into words and - returned on the stream. - error (google.rpc.status_pb2.Status): - The error that is thrown after all words are - sent on the stream. - stream_wait_time (google.protobuf.duration_pb2.Duration): - The wait time between each server streaming - messages - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - stream_wait_time: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - -class PagedExpandRequest(proto.Message): - r"""The request for the PagedExpand method. - - Attributes: - content (str): - The string to expand. - page_size (int): - The number of words to returned in each page. - page_token (str): - The position of the page to be returned. - """ - - content: 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 PagedExpandLegacyRequest(proto.Message): - r"""The request for the PagedExpandLegacy method. This is a - pattern used by some legacy APIs. New APIs should NOT use this - pattern, but rather something like PagedExpandRequest which - conforms to aip.dev/158. - - Attributes: - content (str): - The string to expand. - max_results (int): - The number of words to returned in each page. (-- - aip.dev/not-precedent: This is a legacy, non-standard - pattern that violates aip.dev/158. Ordinarily, this should - be page_size. --) - page_token (str): - The position of the page to be returned. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - max_results: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class PagedExpandResponse(proto.Message): - r"""The response for the PagedExpand method. - - Attributes: - responses (MutableSequence[google.showcase_v1beta1.types.EchoResponse]): - The words that were expanded. - next_page_token (str): - The next page token. - """ - - @property - def raw_page(self): - return self - - responses: MutableSequence['EchoResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EchoResponse', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class PagedExpandResponseList(proto.Message): - r"""A list of words. - - Attributes: - words (MutableSequence[str]): - - """ - - words: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class PagedExpandLegacyMappedResponse(proto.Message): - r""" - - Attributes: - alphabetized (MutableMapping[str, google.showcase_v1beta1.types.PagedExpandResponseList]): - The words that were expanded, indexed by their initial - character. (-- aip.dev/not-precedent: This is a legacy, - non-standard pattern that violates aip.dev/158. Ordinarily, - this should be a ``repeated`` field, as in - PagedExpandResponse. --) - next_page_token (str): - The next page token. - """ - - @property - def raw_page(self): - return self - - alphabetized: MutableMapping[str, 'PagedExpandResponseList'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='PagedExpandResponseList', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class WaitRequest(proto.Message): - r"""The request for Wait method. - - 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: - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time that this operation will complete. - - This field is a member of `oneof`_ ``end``. - ttl (google.protobuf.duration_pb2.Duration): - The duration of this operation. - - This field is a member of `oneof`_ ``end``. - error (google.rpc.status_pb2.Status): - The error that will be returned by the - server. If this code is specified to be the OK - rpc code, an empty response will be returned. - - This field is a member of `oneof`_ ``response``. - success (google.showcase_v1beta1.types.WaitResponse): - The response to be returned on operation - completion. - - This field is a member of `oneof`_ ``response``. - """ - - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - oneof='end', - message=timestamp_pb2.Timestamp, - ) - ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - oneof='end', - message=duration_pb2.Duration, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - oneof='response', - message=status_pb2.Status, - ) - success: 'WaitResponse' = proto.Field( - proto.MESSAGE, - number=3, - oneof='response', - message='WaitResponse', - ) - - -class WaitResponse(proto.Message): - r"""The result of the Wait operation. - - Attributes: - content (str): - This content of the result. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - - -class WaitMetadata(proto.Message): - r"""The metadata for Wait operation. - - Attributes: - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time that this operation will complete. - """ - - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - - -class BlockRequest(proto.Message): - r"""The request for Block method. - - 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: - response_delay (google.protobuf.duration_pb2.Duration): - The amount of time to block before returning - a response. - error (google.rpc.status_pb2.Status): - The error that will be returned by the - server. If this code is specified to be the OK - rpc code, an empty response will be returned. - - This field is a member of `oneof`_ ``response``. - success (google.showcase_v1beta1.types.BlockResponse): - The response to be returned that will signify - successful method call. - - This field is a member of `oneof`_ ``response``. - """ - - response_delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - oneof='response', - message=status_pb2.Status, - ) - success: 'BlockResponse' = proto.Field( - proto.MESSAGE, - number=3, - oneof='response', - message='BlockResponse', - ) - - -class BlockResponse(proto.Message): - r"""The response for Block method. - - Attributes: - content (str): - This content can contain anything, the server - will not depend on a value here. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py deleted file mode 100644 index c2e1346e8f3f..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/identity.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.showcase.v1beta1', - manifest={ - 'User', - 'CreateUserRequest', - 'GetUserRequest', - 'UpdateUserRequest', - 'DeleteUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - }, -) - - -class User(proto.Message): - r"""A user. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the user. - display_name (str): - The display_name of the user. - email (str): - The email address of the user. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the user was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The latest timestamp at which the user was - updated. - age (int): - The age of the user in years. - - This field is a member of `oneof`_ ``_age``. - height_feet (float): - The height of the user in feet. - - This field is a member of `oneof`_ ``_height_feet``. - nickname (str): - The nickname of the user. - - (-- aip.dev/not-precedent: An empty string is a valid - nickname. Ordinarily, proto3_optional should not be used on - a ``string`` field. --) - - This field is a member of `oneof`_ ``_nickname``. - enable_notifications (bool): - Enables the receiving of notifications. The default is true - if unset. - - (-- aip.dev/not-precedent: The default for the feature is - true. Ordinarily, the default for a ``bool`` field should be - false. --) - - This field is a member of `oneof`_ ``_enable_notifications``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - email: 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, - ) - age: int = proto.Field( - proto.INT32, - number=6, - optional=True, - ) - height_feet: float = proto.Field( - proto.DOUBLE, - number=7, - optional=True, - ) - nickname: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - enable_notifications: bool = proto.Field( - proto.BOOL, - number=9, - optional=True, - ) - - -class CreateUserRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Identity\CreateUser method. - - Attributes: - user (google.showcase_v1beta1.types.User): - The user to create. - """ - - user: 'User' = proto.Field( - proto.MESSAGE, - number=1, - message='User', - ) - - -class GetUserRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Identity\GetUser method. - - Attributes: - name (str): - The resource name of the requested user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateUserRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Identity\UpdateUser method. - - Attributes: - user (google.showcase_v1beta1.types.User): - The user to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The field mask to determine which fields are - to be updated. If empty, the server will assume - all fields are to be updated. - """ - - user: 'User' = proto.Field( - proto.MESSAGE, - number=1, - message='User', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteUserRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Identity\DeleteUser method. - - Attributes: - name (str): - The resource name of the user to delete. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListUsersRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Identity\ListUsers method. - - Attributes: - page_size (int): - The maximum number of users to return. Server - may return fewer users than requested. If - unspecified, server will pick an appropriate - default. - page_token (str): - The value of - google.showcase.v1beta1.ListUsersResponse.next_page_token - returned from the previous call to - ``google.showcase.v1beta1.Identity\ListUsers`` method. - """ - - page_size: int = proto.Field( - proto.INT32, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListUsersResponse(proto.Message): - r"""The response message for the - google.showcase.v1beta1.Identity\ListUsers method. - - Attributes: - users (MutableSequence[google.showcase_v1beta1.types.User]): - The list of users. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - ListUsersRequest.page_token field in the subsequent call to - ``google.showcase.v1beta1.Message\ListUsers`` method to - retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - users: MutableSequence['User'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='User', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py b/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py deleted file mode 100644 index 0843ea5da7d1..000000000000 --- a/packages/gapic-generator/generated_showcase/google/showcase_v1beta1/types/messaging.py +++ /dev/null @@ -1,668 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -import google.rpc.error_details_pb2 as error_details_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.showcase.v1beta1', - manifest={ - 'Room', - 'CreateRoomRequest', - 'GetRoomRequest', - 'UpdateRoomRequest', - 'DeleteRoomRequest', - 'ListRoomsRequest', - 'ListRoomsResponse', - 'Blurb', - 'CreateBlurbRequest', - 'GetBlurbRequest', - 'UpdateBlurbRequest', - 'DeleteBlurbRequest', - 'ListBlurbsRequest', - 'ListBlurbsResponse', - 'SearchBlurbsRequest', - 'SearchBlurbsMetadata', - 'SearchBlurbsResponse', - 'StreamBlurbsRequest', - 'StreamBlurbsResponse', - 'SendBlurbsResponse', - 'ConnectRequest', - }, -) - - -class Room(proto.Message): - r"""A chat room. - - Attributes: - name (str): - The resource name of the chat room. - display_name (str): - The human readable name of the chat room. - description (str): - The description of the chat room. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the room was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The latest timestamp at which the room was - updated. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class CreateRoomRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\CreateRoom method. - - Attributes: - room (google.showcase_v1beta1.types.Room): - The room to create. - """ - - room: 'Room' = proto.Field( - proto.MESSAGE, - number=1, - message='Room', - ) - - -class GetRoomRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\GetRoom method. - - Attributes: - name (str): - The resource name of the requested room. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateRoomRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\UpdateRoom method. - - Attributes: - room (google.showcase_v1beta1.types.Room): - The room to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The field mask to determine which fields are - to be updated. If empty, the server will assume - all fields are to be updated. - """ - - room: 'Room' = proto.Field( - proto.MESSAGE, - number=1, - message='Room', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteRoomRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\DeleteRoom method. - - Attributes: - name (str): - The resource name of the requested room. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListRoomsRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\ListRooms method. - - Attributes: - page_size (int): - The maximum number of rooms return. Server - may return fewer rooms than requested. If - unspecified, server will pick an appropriate - default. - page_token (str): - The value of - google.showcase.v1beta1.ListRoomsResponse.next_page_token - returned from the previous call to - ``google.showcase.v1beta1.Messaging\ListRooms`` method. - """ - - page_size: int = proto.Field( - proto.INT32, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListRoomsResponse(proto.Message): - r"""The response message for the - google.showcase.v1beta1.Messaging\ListRooms method. - - Attributes: - rooms (MutableSequence[google.showcase_v1beta1.types.Room]): - The list of rooms. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - ListRoomsRequest.page_token field in the subsequent call to - ``google.showcase.v1beta1.Messaging\ListRooms`` method to - retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - rooms: MutableSequence['Room'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Room', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Blurb(proto.Message): - r"""This protocol buffer message represents a blurb sent to a - chat room or posted on a user profile. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the chat room. - user (str): - The resource name of the blurb's author. - text (str): - The textual content of this blurb. - - This field is a member of `oneof`_ ``content``. - image (bytes): - The image content of this blurb. - - This field is a member of `oneof`_ ``content``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the blurb was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The latest timestamp at which the blurb was - updated. - legacy_room_id (str): - The legacy id of the room. This field is used to signal the - use of the compound resource pattern - ``rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}`` - - This field is a member of `oneof`_ ``legacy_id``. - legacy_user_id (str): - The legacy id of the user. This field is used to signal the - use of the compound resource pattern - ``users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}`` - - This field is a member of `oneof`_ ``legacy_id``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - user: str = proto.Field( - proto.STRING, - number=2, - ) - text: str = proto.Field( - proto.STRING, - number=3, - oneof='content', - ) - image: bytes = proto.Field( - proto.BYTES, - number=4, - oneof='content', - ) - 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, - ) - legacy_room_id: str = proto.Field( - proto.STRING, - number=7, - oneof='legacy_id', - ) - legacy_user_id: str = proto.Field( - proto.STRING, - number=8, - oneof='legacy_id', - ) - - -class CreateBlurbRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\CreateBlurb method. - - Attributes: - parent (str): - The resource name of the chat room or user - profile that this blurb will be tied to. - blurb (google.showcase_v1beta1.types.Blurb): - The blurb to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - blurb: 'Blurb' = proto.Field( - proto.MESSAGE, - number=2, - message='Blurb', - ) - - -class GetBlurbRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\GetBlurb method. - - Attributes: - name (str): - The resource name of the requested blurb. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateBlurbRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\UpdateBlurb method. - - Attributes: - blurb (google.showcase_v1beta1.types.Blurb): - The blurb to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The field mask to determine wich fields are - to be updated. If empty, the server will assume - all fields are to be updated. - """ - - blurb: 'Blurb' = proto.Field( - proto.MESSAGE, - number=1, - message='Blurb', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteBlurbRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\DeleteBlurb method. - - Attributes: - name (str): - The resource name of the requested blurb. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListBlurbsRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\ListBlurbs method. - - Attributes: - parent (str): - The resource name of the requested room or - profile whos blurbs to list. - page_size (int): - The maximum number of blurbs to return. - Server may return fewer blurbs than requested. - If unspecified, server will pick an appropriate - default. - page_token (str): - The value of - google.showcase.v1beta1.ListBlurbsResponse.next_page_token - returned from the previous call to - ``google.showcase.v1beta1.Messaging\ListBlurbs`` method. - """ - - 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 ListBlurbsResponse(proto.Message): - r"""The response message for the - google.showcase.v1beta1.Messaging\ListBlurbs method. - - Attributes: - blurbs (MutableSequence[google.showcase_v1beta1.types.Blurb]): - The list of blurbs. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - ListBlurbsRequest.page_token field in the subsequent call to - ``google.showcase.v1beta1.Blurb\ListBlurbs`` method to - retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - blurbs: MutableSequence['Blurb'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Blurb', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchBlurbsRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\SearchBlurbs method. - - Attributes: - query (str): - The query used to search for blurbs - containing to words of this string. Only posts - that contain an exact match of a queried word - will be returned. - parent (str): - The rooms or profiles to search. If unset, ``SearchBlurbs`` - will search all rooms and all profiles. - page_size (int): - The maximum number of blurbs return. Server - may return fewer blurbs than requested. If - unspecified, server will pick an appropriate - default. - page_token (str): - The value of - google.showcase.v1beta1.SearchBlurbsResponse.next_page_token - returned from the previous call to - ``google.showcase.v1beta1.Messaging\SearchBlurbs`` method. - """ - - query: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchBlurbsMetadata(proto.Message): - r"""The operation metadata message for the - google.showcase.v1beta1.Messaging\SearchBlurbs method. - - Attributes: - retry_info (google.rpc.error_details_pb2.RetryInfo): - This signals to the client when to next poll - for response. - """ - - retry_info: error_details_pb2.RetryInfo = proto.Field( - proto.MESSAGE, - number=1, - message=error_details_pb2.RetryInfo, - ) - - -class SearchBlurbsResponse(proto.Message): - r"""The operation response message for the - google.showcase.v1beta1.Messaging\SearchBlurbs method. - - Attributes: - blurbs (MutableSequence[google.showcase_v1beta1.types.Blurb]): - Blurbs that matched the search query. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - SearchBlurbsRequest.page_token field in the subsequent call - to ``google.showcase.v1beta1.Blurb\SearchBlurbs`` method to - retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - blurbs: MutableSequence['Blurb'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Blurb', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class StreamBlurbsRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\StreamBlurbs method. - - Attributes: - name (str): - The resource name of a chat room or user - profile whose blurbs to stream. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which this stream will close. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class StreamBlurbsResponse(proto.Message): - r"""The response message for the - google.showcase.v1beta1.Messaging\StreamBlurbs method. - - Attributes: - blurb (google.showcase_v1beta1.types.Blurb): - The blurb that was either created, updated, - or deleted. - action (google.showcase_v1beta1.types.StreamBlurbsResponse.Action): - The action that triggered the blurb to be - returned. - """ - class Action(proto.Enum): - r"""The action that triggered the blurb to be returned. - - Values: - ACTION_UNSPECIFIED (0): - No description available. - CREATE (1): - Specifies that the blurb was created. - UPDATE (2): - Specifies that the blurb was updated. - DELETE (3): - Specifies that the blurb was deleted. - """ - ACTION_UNSPECIFIED = 0 - CREATE = 1 - UPDATE = 2 - DELETE = 3 - - blurb: 'Blurb' = proto.Field( - proto.MESSAGE, - number=1, - message='Blurb', - ) - action: Action = proto.Field( - proto.ENUM, - number=2, - enum=Action, - ) - - -class SendBlurbsResponse(proto.Message): - r"""The response message for the - google.showcase.v1beta1.Messaging\SendBlurbs method. - - Attributes: - names (MutableSequence[str]): - The names of successful blurb creations. - """ - - names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class ConnectRequest(proto.Message): - r"""The request message for the - google.showcase.v1beta1.Messaging\Connect method. - - 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: - config (google.showcase_v1beta1.types.ConnectRequest.ConnectConfig): - Provides information that specifies how to process - subsequent requests. The first ``ConnectRequest`` message - must contain a ``config`` message. - - This field is a member of `oneof`_ ``request``. - blurb (google.showcase_v1beta1.types.Blurb): - The blurb to be created. - - This field is a member of `oneof`_ ``request``. - """ - - class ConnectConfig(proto.Message): - r""" - - Attributes: - parent (str): - The room or profile to follow and create - messages for. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - config: ConnectConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='request', - message=ConnectConfig, - ) - blurb: 'Blurb' = proto.Field( - proto.MESSAGE, - number=2, - oneof='request', - message='Blurb', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/gapic-generator/generated_showcase/noxfile.py b/packages/gapic-generator/generated_showcase/noxfile.py deleted file mode 100644 index 0bd125534ee2..000000000000 --- a/packages/gapic-generator/generated_showcase/noxfile.py +++ /dev/null @@ -1,635 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - -from typing import Dict, List -import warnings - -import nox - -RUFF_VERSION = "ruff==0.14.14" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -# Add samples to the list of directories to format if the directory exists. -if os.path.isdir("samples"): - LINT_PATHS.append("samples") - -ALL_PYTHON = [ - "3.10", - "3.11", - "3.12", - "3.13", - "3.14", - "3.15", -] - -DEFAULT_PYTHON_VERSION = "3.14" - -PREVIEW_PYTHON_VERSION = "3.15" - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() -# Path to the centralized mypy configuration file at the repository root. -# Search upwards to support running nox from both monorepo packages and integration test goldens. -MYPY_CONFIG_FILE = next( - (str(p / "mypy.ini") for p in CURRENT_DIRECTORY.parents if (p / "mypy.ini").exists()), - str(CURRENT_DIRECTORY.parent.parent / "mypy.ini"), -) - -if (CURRENT_DIRECTORY / "testing").exists(): - LOWER_BOUND_CONSTRAINTS_FILE = ( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt" - ) -else: - LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-showcase" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ALL_PYTHON -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2579): - # use the latest version of mypy - session.install( - "mypy<1.16.0", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - f"--config-file={MYPY_CONFIG_FILE}", - "-p", - "google", - "--check-untyped-defs", - *session.posargs, - ) - - -@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 lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", RUFF_VERSION) - - # 2. Check formatting - session.run( - "ruff", "format", - "--check", - f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", - "--line-length=88", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """(Deprecated) Legacy session. Please use 'nox -s format'.""" - session.log("WARNING: The 'blacken' session is deprecated and will be removed in a future release. Please use 'nox -s format' in the future.") - - # Just run the ruff formatter (keeping legacy behavior of only formatting, not sorting imports) - session.install(RUFF_VERSION) - session.run( - "ruff", "format", - f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", - "--line-length=88", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run ruff to sort imports and format code. - """ - # 1. Install ruff (skipped automatically if you run with --no-venv) - session.install(RUFF_VERSION) - - # 2. Run Ruff to fix imports - # check --select I: Enables strict import sorting - # --fix: Applies the changes automatically - session.run( - "ruff", "check", - "--select", "I", - "--fix", - f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", - "--line-length=88", # Standard Black line length - *LINT_PATHS, - ) - - # 3. Run Ruff to format code - session.run( - "ruff", "format", - f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", - "--line-length=88", # Standard Black line length - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - if session.python >= "3.12": - session.install("--pre", "grpcio>=1.75.1") - else: - session.install("--pre", "grpcio<=1.62.2") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.0", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-b", "html", # builder - "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory - # paths to build: - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=PREVIEW_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all 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 - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio>=1.75.1" if session.python >= "3.12" else "grpcio<=1.62.2", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - deps_dir = CURRENT_DIRECTORY.parent - while deps_dir.name != "packages" and deps_dir.parent != deps_dir: - deps_dir = deps_dir.parent - - # Extract the base package name, safely ignoring version bounds and spaces - # (e.g., "grpcio>=1.75.1" becomes "grpcio") - parsed_deps = { - dep: re.match(r"^([a-zA-Z0-9_-]+)", dep).group(1) - for dep in prerel_deps - } - - # Dynamically sort local packages vs PyPI dependencies - local_paths = [] - pypi_deps = [] - - for dep, pkg_name in parsed_deps.items(): - if (deps_dir / pkg_name).exists(): - local_paths.append(str(deps_dir / pkg_name)) - else: - pypi_deps.append(dep) - - # Batch pip installations to avoid sequential overhead - if local_paths: - session.install(*local_paths, "--no-deps", "--ignore-installed") - if pypi_deps: - session.install(*pypi_deps, "--pre", "--no-deps", "--ignore-installed") - - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - # Reuse the parsed names for logging and version verification - for dep, pkg_name in parsed_deps.items(): - print(f"Installed {dep}") - version_namespace = package_namespaces.get(pkg_name) - - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=PREVIEW_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all 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 - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "proto-plus", - ] - - deps_dir = CURRENT_DIRECTORY.parent - while deps_dir.name != "packages" and deps_dir.parent != deps_dir: - deps_dir = deps_dir.parent - - # Batch the pip installation to avoid sequential overhead - dep_paths = [str(deps_dir / dep) for dep in core_dependencies_from_source] - - session.install(*dep_paths, "--no-deps", "--ignore-installed") - print(f"Installed {', '.join(core_dependencies_from_source)} locally from {deps_dir}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py deleted file mode 100644 index ccfa4c54c81e..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Block -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Block_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_block(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.BlockRequest( - ) - - # Make the request - response = await client.block(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Block_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py deleted file mode 100644 index 793a37968c5f..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_block_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Block -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Block_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_block(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.BlockRequest( - ) - - # Make the request - response = client.block(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Block_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py deleted file mode 100644 index 6e52dedc77f1..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Chat -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Chat_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_chat(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.chat(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Chat_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py deleted file mode 100644 index 8b6916a40d86..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_chat_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Chat -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Chat_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_chat(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.chat(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Chat_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py deleted file mode 100644 index f27f28952799..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Collect -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Collect_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_collect(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = await client.collect(requests=request_generator()) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Collect_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py deleted file mode 100644 index 88d9cc06d0ac..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_collect_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Collect -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Collect_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_collect(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.EchoRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = client.collect(requests=request_generator()) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Collect_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py deleted file mode 100644 index 8d2939515521..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Echo -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Echo_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_echo(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # Make the request - response = await client.echo(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Echo_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py deleted file mode 100644 index 61d1cedb770f..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EchoErrorDetails -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_echo_error_details(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoErrorDetailsRequest( - ) - - # Make the request - response = await client.echo_error_details(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py deleted file mode 100644 index 80d6ab4e0bb3..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EchoErrorDetails -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_echo_error_details(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoErrorDetailsRequest( - ) - - # Make the request - response = client.echo_error_details(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py deleted file mode 100644 index 8be25fdad6aa..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_echo_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Echo -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Echo_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_echo(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.EchoRequest( - content="content_value", - ) - - # Make the request - response = client.echo(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Echo_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py deleted file mode 100644 index 577d5ad90ef4..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Expand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Expand_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_expand(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ExpandRequest( - ) - - # Make the request - stream = await client.expand(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Expand_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py deleted file mode 100644 index e7e36ecd9c26..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_expand_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Expand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Expand_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_expand(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ExpandRequest( - ) - - # Make the request - stream = client.expand(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Expand_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py deleted file mode 100644 index 71b07b122d22..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PagedExpand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_PagedExpand_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_paged_expand(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_PagedExpand_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py deleted file mode 100644 index 8f6dba9bdd67..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PagedExpandLegacy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_paged_expand_legacy(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandLegacyRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py deleted file mode 100644 index fb80b5a96ee9..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PagedExpandLegacyMapped -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_paged_expand_legacy_mapped(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy_mapped(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py deleted file mode 100644 index 4eb8314f58f1..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PagedExpandLegacyMapped -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_paged_expand_legacy_mapped(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy_mapped(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py deleted file mode 100644 index 8f2706bbdcfa..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PagedExpandLegacy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_paged_expand_legacy(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandLegacyRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand_legacy(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py deleted file mode 100644 index 67bd7840c35f..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_paged_expand_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PagedExpand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_PagedExpand_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_paged_expand(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.PagedExpandRequest( - content="content_value", - ) - - # Make the request - page_result = client.paged_expand(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_PagedExpand_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py deleted file mode 100644 index 4414bf510efb..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Wait -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Wait_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_wait(): - # Create a client - client = showcase_v1beta1.EchoAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.WaitRequest( - ) - - # Make the request - operation = await client.wait(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Wait_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py deleted file mode 100644 index 4dc408d6ae76..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_echo_wait_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Wait -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Echo_Wait_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_wait(): - # Create a client - client = showcase_v1beta1.EchoClient() - - # Initialize request argument(s) - request = showcase_v1beta1.WaitRequest( - ) - - # Make the request - operation = client.wait(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Echo_Wait_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py deleted file mode 100644 index 6630faac2b2d..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_CreateUser_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_create_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateUserRequest( - ) - - # Make the request - response = await client.create_user(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_CreateUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py deleted file mode 100644 index 249cfce8edb8..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_create_user_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_CreateUser_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_create_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateUserRequest( - ) - - # Make the request - response = client.create_user(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_CreateUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py deleted file mode 100644 index e263fb8eeaa1..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_DeleteUser_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_delete_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteUserRequest( - name="name_value", - ) - - # Make the request - await client.delete_user(request=request) - - -# [END localhost:7469_v1beta1_generated_Identity_DeleteUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py deleted file mode 100644 index 463d7bc7f745..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_delete_user_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_DeleteUser_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_delete_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteUserRequest( - name="name_value", - ) - - # Make the request - client.delete_user(request=request) - - -# [END localhost:7469_v1beta1_generated_Identity_DeleteUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py deleted file mode 100644 index 38a3a2d62d86..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_GetUser_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_get_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetUserRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_GetUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py deleted file mode 100644 index bf9a19b673ff..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_get_user_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_GetUser_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_get_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetUserRequest( - name="name_value", - ) - - # Make the request - response = client.get_user(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_GetUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py deleted file mode 100644 index 5464905cbeb2..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_ListUsers_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_list_users(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListUsersRequest( - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_ListUsers_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py deleted file mode 100644 index 91524f9f68c2..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_list_users_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_ListUsers_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_list_users(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListUsersRequest( - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_ListUsers_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py deleted file mode 100644 index 2a8e502c902e..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_UpdateUser_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_update_user(): - # Create a client - client = showcase_v1beta1.IdentityAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateUserRequest( - ) - - # Make the request - response = await client.update_user(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_UpdateUser_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py deleted file mode 100644 index ba15ed5eec2c..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_identity_update_user_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUser -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Identity_UpdateUser_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_update_user(): - # Create a client - client = showcase_v1beta1.IdentityClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateUserRequest( - ) - - # Make the request - response = client.update_user(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Identity_UpdateUser_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py deleted file mode 100644 index 48dac27bf485..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Connect -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_Connect_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_connect(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ConnectRequest( - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.ConnectRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.connect(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_Connect_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py deleted file mode 100644 index d9e5f9c128d0..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_connect_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Connect -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_Connect_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_connect(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ConnectRequest( - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.ConnectRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.connect(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_Connect_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py deleted file mode 100644 index 93e4bc2186f7..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_CreateBlurb_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_create_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_blurb(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_CreateBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py deleted file mode 100644 index 0300a179f538..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_CreateBlurb_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_create_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_blurb(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_CreateBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py deleted file mode 100644 index 6d68319ce5ce..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_CreateRoom_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_create_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateRoomRequest( - ) - - # Make the request - response = await client.create_room(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_CreateRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py deleted file mode 100644 index 0b82661bd0c7..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_create_room_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_CreateRoom_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_create_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateRoomRequest( - ) - - # Make the request - response = client.create_room(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_CreateRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py deleted file mode 100644 index 85defa14ff6f..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_delete_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteBlurbRequest( - name="name_value", - ) - - # Make the request - await client.delete_blurb(request=request) - - -# [END localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py deleted file mode 100644 index 4076b61b058a..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_delete_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteBlurbRequest( - name="name_value", - ) - - # Make the request - client.delete_blurb(request=request) - - -# [END localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py deleted file mode 100644 index 45d408b11548..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_DeleteRoom_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_delete_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteRoomRequest( - name="name_value", - ) - - # Make the request - await client.delete_room(request=request) - - -# [END localhost:7469_v1beta1_generated_Messaging_DeleteRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py deleted file mode 100644 index 780e34918d10..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_delete_room_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_DeleteRoom_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_delete_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.DeleteRoomRequest( - name="name_value", - ) - - # Make the request - client.delete_room(request=request) - - -# [END localhost:7469_v1beta1_generated_Messaging_DeleteRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py deleted file mode 100644 index 8e702f32fa7d..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_GetBlurb_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_get_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetBlurbRequest( - name="name_value", - ) - - # Make the request - response = await client.get_blurb(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_GetBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py deleted file mode 100644 index a6445d43844b..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_GetBlurb_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_get_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetBlurbRequest( - name="name_value", - ) - - # Make the request - response = client.get_blurb(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_GetBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py deleted file mode 100644 index 4163de2cb223..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_GetRoom_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_get_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetRoomRequest( - name="name_value", - ) - - # Make the request - response = await client.get_room(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_GetRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py deleted file mode 100644 index cc44db0dc51f..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_get_room_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_GetRoom_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_get_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.GetRoomRequest( - name="name_value", - ) - - # Make the request - response = client.get_room(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_GetRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py deleted file mode 100644 index 95751b3924b0..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_ListBlurbs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_list_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListBlurbsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_blurbs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_ListBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py deleted file mode 100644 index 8089c0f6e2b2..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_ListBlurbs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_list_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListBlurbsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_blurbs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_ListBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py deleted file mode 100644 index 8918c51b6496..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRooms -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_ListRooms_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_list_rooms(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListRoomsRequest( - ) - - # Make the request - page_result = client.list_rooms(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_ListRooms_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py deleted file mode 100644 index 86d8a78152a2..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRooms -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_ListRooms_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_list_rooms(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.ListRoomsRequest( - ) - - # Make the request - page_result = client.list_rooms(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_ListRooms_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py deleted file mode 100644 index d73d46d571df..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_search_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.SearchBlurbsRequest( - query="query_value", - ) - - # Make the request - operation = await client.search_blurbs(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py deleted file mode 100644 index 0f3a9fee5b3d..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_search_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.SearchBlurbsRequest( - query="query_value", - ) - - # Make the request - operation = client.search_blurbs(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py deleted file mode 100644 index b7f2a6591356..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SendBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_SendBlurbs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_send_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.CreateBlurbRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = await client.send_blurbs(requests=request_generator()) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_SendBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py deleted file mode 100644 index 8f899913c3a6..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SendBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_SendBlurbs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_send_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.CreateBlurbRequest( - parent="parent_value", - ) - - # This method expects an iterator which contains - # 'showcase_v1beta1.CreateBlurbRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - response = client.send_blurbs(requests=request_generator()) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_SendBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py deleted file mode 100644 index b787a1e06bc0..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_stream_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.StreamBlurbsRequest( - name="name_value", - ) - - # Make the request - stream = await client.stream_blurbs(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py deleted file mode 100644 index cf1f64485c01..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamBlurbs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_stream_blurbs(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.StreamBlurbsRequest( - name="name_value", - ) - - # Make the request - stream = client.stream_blurbs(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py deleted file mode 100644 index b5448a10ed2e..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_update_blurb(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateBlurbRequest( - ) - - # Make the request - response = await client.update_blurb(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py deleted file mode 100644 index 4e774d3135a3..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateBlurb -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_update_blurb(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateBlurbRequest( - ) - - # Make the request - response = client.update_blurb(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py deleted file mode 100644 index c37973a377a4..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_UpdateRoom_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -async def sample_update_room(): - # Create a client - client = showcase_v1beta1.MessagingAsyncClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateRoomRequest( - ) - - # Make the request - response = await client.update_room(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_UpdateRoom_async] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py b/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py deleted file mode 100644 index 7eb0773a95c6..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/localhost:7469_v1beta1_generated_messaging_update_room_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateRoom -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-showcase - - -# [START localhost:7469_v1beta1_generated_Messaging_UpdateRoom_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google import showcase_v1beta1 - - -def sample_update_room(): - # Create a client - client = showcase_v1beta1.MessagingClient() - - # Initialize request argument(s) - request = showcase_v1beta1.UpdateRoomRequest( - ) - - # Make the request - response = client.update_room(request=request) - - # Handle the response - print(response) - -# [END localhost:7469_v1beta1_generated_Messaging_UpdateRoom_sync] diff --git a/packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json b/packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json deleted file mode 100644 index d5032e271d38..000000000000 --- a/packages/gapic-generator/generated_showcase/samples/generated_samples/snippet_metadata_google.showcase.v1beta1.json +++ /dev/null @@ -1,4618 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.showcase.v1beta1", - "version": "v1beta1" - } - ], - "language": "PYTHON", - "name": "google-showcase", - "version": "0.0.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.block", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Block", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Block" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.BlockRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.BlockResponse", - "shortName": "block" - }, - "description": "Sample for Block", - "file": "localhost:7469_v1beta1_generated_echo_block_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Block_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_block_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.block", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Block", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Block" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.BlockRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.BlockResponse", - "shortName": "block" - }, - "description": "Sample for Block", - "file": "localhost:7469_v1beta1_generated_echo_block_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Block_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_block_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.chat", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Chat", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Chat" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", - "shortName": "chat" - }, - "description": "Sample for Chat", - "file": "localhost:7469_v1beta1_generated_echo_chat_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Chat_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_chat_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.chat", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Chat", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Chat" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", - "shortName": "chat" - }, - "description": "Sample for Chat", - "file": "localhost:7469_v1beta1_generated_echo_chat_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Chat_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_chat_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.collect", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Collect", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Collect" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.EchoResponse", - "shortName": "collect" - }, - "description": "Sample for Collect", - "file": "localhost:7469_v1beta1_generated_echo_collect_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Collect_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_collect_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.collect", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Collect", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Collect" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.EchoRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.EchoResponse", - "shortName": "collect" - }, - "description": "Sample for Collect", - "file": "localhost:7469_v1beta1_generated_echo_collect_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Collect_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_collect_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.echo_error_details", - "method": { - "fullName": "google.showcase.v1beta1.Echo.EchoErrorDetails", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "EchoErrorDetails" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.EchoErrorDetailsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.EchoErrorDetailsResponse", - "shortName": "echo_error_details" - }, - "description": "Sample for EchoErrorDetails", - "file": "localhost:7469_v1beta1_generated_echo_echo_error_details_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_echo_error_details_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.echo_error_details", - "method": { - "fullName": "google.showcase.v1beta1.Echo.EchoErrorDetails", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "EchoErrorDetails" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.EchoErrorDetailsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.EchoErrorDetailsResponse", - "shortName": "echo_error_details" - }, - "description": "Sample for EchoErrorDetails", - "file": "localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_EchoErrorDetails_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_echo_error_details_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.echo", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Echo", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Echo" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.EchoRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.EchoResponse", - "shortName": "echo" - }, - "description": "Sample for Echo", - "file": "localhost:7469_v1beta1_generated_echo_echo_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Echo_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": "localhost:7469_v1beta1_generated_echo_echo_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.echo", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Echo", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Echo" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.EchoRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.EchoResponse", - "shortName": "echo" - }, - "description": "Sample for Echo", - "file": "localhost:7469_v1beta1_generated_echo_echo_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Echo_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": "localhost:7469_v1beta1_generated_echo_echo_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.expand", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Expand", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Expand" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ExpandRequest" - }, - { - "name": "content", - "type": "str" - }, - { - "name": "error", - "type": "google.rpc.status_pb2.Status" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", - "shortName": "expand" - }, - "description": "Sample for Expand", - "file": "localhost:7469_v1beta1_generated_echo_expand_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Expand_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_expand_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.expand", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Expand", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Expand" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ExpandRequest" - }, - { - "name": "content", - "type": "str" - }, - { - "name": "error", - "type": "google.rpc.status_pb2.Status" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.EchoResponse]", - "shortName": "expand" - }, - "description": "Sample for Expand", - "file": "localhost:7469_v1beta1_generated_echo_expand_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Expand_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_echo_expand_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.paged_expand_legacy_mapped", - "method": { - "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacyMapped", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "PagedExpandLegacyMapped" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.PagedExpandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedAsyncPager", - "shortName": "paged_expand_legacy_mapped" - }, - "description": "Sample for PagedExpandLegacyMapped", - "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.paged_expand_legacy_mapped", - "method": { - "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacyMapped", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "PagedExpandLegacyMapped" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.PagedExpandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyMappedPager", - "shortName": "paged_expand_legacy_mapped" - }, - "description": "Sample for PagedExpandLegacyMapped", - "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacyMapped_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_mapped_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.paged_expand_legacy", - "method": { - "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacy", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "PagedExpandLegacy" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.PagedExpandLegacyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyAsyncPager", - "shortName": "paged_expand_legacy" - }, - "description": "Sample for PagedExpandLegacy", - "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.paged_expand_legacy", - "method": { - "fullName": "google.showcase.v1beta1.Echo.PagedExpandLegacy", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "PagedExpandLegacy" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.PagedExpandLegacyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandLegacyPager", - "shortName": "paged_expand_legacy" - }, - "description": "Sample for PagedExpandLegacy", - "file": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpandLegacy_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": "localhost:7469_v1beta1_generated_echo_paged_expand_legacy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.paged_expand", - "method": { - "fullName": "google.showcase.v1beta1.Echo.PagedExpand", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "PagedExpand" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.PagedExpandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandAsyncPager", - "shortName": "paged_expand" - }, - "description": "Sample for PagedExpand", - "file": "localhost:7469_v1beta1_generated_echo_paged_expand_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpand_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": "localhost:7469_v1beta1_generated_echo_paged_expand_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.paged_expand", - "method": { - "fullName": "google.showcase.v1beta1.Echo.PagedExpand", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "PagedExpand" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.PagedExpandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.echo.pagers.PagedExpandPager", - "shortName": "paged_expand" - }, - "description": "Sample for PagedExpand", - "file": "localhost:7469_v1beta1_generated_echo_paged_expand_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_PagedExpand_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": "localhost:7469_v1beta1_generated_echo_paged_expand_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.EchoAsyncClient", - "shortName": "EchoAsyncClient" - }, - "fullName": "google.showcase_v1beta1.EchoAsyncClient.wait", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Wait", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Wait" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.WaitRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "wait" - }, - "description": "Sample for Wait", - "file": "localhost:7469_v1beta1_generated_echo_wait_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Wait_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": "localhost:7469_v1beta1_generated_echo_wait_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.EchoClient", - "shortName": "EchoClient" - }, - "fullName": "google.showcase_v1beta1.EchoClient.wait", - "method": { - "fullName": "google.showcase.v1beta1.Echo.Wait", - "service": { - "fullName": "google.showcase.v1beta1.Echo", - "shortName": "Echo" - }, - "shortName": "Wait" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.WaitRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "wait" - }, - "description": "Sample for Wait", - "file": "localhost:7469_v1beta1_generated_echo_wait_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Echo_Wait_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": "localhost:7469_v1beta1_generated_echo_wait_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.IdentityAsyncClient", - "shortName": "IdentityAsyncClient" - }, - "fullName": "google.showcase_v1beta1.IdentityAsyncClient.create_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.CreateUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "CreateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.CreateUserRequest" - }, - { - "name": "display_name", - "type": "str" - }, - { - "name": "email", - "type": "str" - }, - { - "name": "age", - "type": "int" - }, - { - "name": "nickname", - "type": "str" - }, - { - "name": "enable_notifications", - "type": "bool" - }, - { - "name": "height_feet", - "type": "float" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.User", - "shortName": "create_user" - }, - "description": "Sample for CreateUser", - "file": "localhost:7469_v1beta1_generated_identity_create_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_CreateUser_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_create_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.IdentityClient", - "shortName": "IdentityClient" - }, - "fullName": "google.showcase_v1beta1.IdentityClient.create_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.CreateUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "CreateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.CreateUserRequest" - }, - { - "name": "display_name", - "type": "str" - }, - { - "name": "email", - "type": "str" - }, - { - "name": "age", - "type": "int" - }, - { - "name": "nickname", - "type": "str" - }, - { - "name": "enable_notifications", - "type": "bool" - }, - { - "name": "height_feet", - "type": "float" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.User", - "shortName": "create_user" - }, - "description": "Sample for CreateUser", - "file": "localhost:7469_v1beta1_generated_identity_create_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_CreateUser_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_create_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.IdentityAsyncClient", - "shortName": "IdentityAsyncClient" - }, - "fullName": "google.showcase_v1beta1.IdentityAsyncClient.delete_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.DeleteUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "DeleteUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.DeleteUserRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_user" - }, - "description": "Sample for DeleteUser", - "file": "localhost:7469_v1beta1_generated_identity_delete_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_DeleteUser_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_delete_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.IdentityClient", - "shortName": "IdentityClient" - }, - "fullName": "google.showcase_v1beta1.IdentityClient.delete_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.DeleteUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "DeleteUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.DeleteUserRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_user" - }, - "description": "Sample for DeleteUser", - "file": "localhost:7469_v1beta1_generated_identity_delete_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_DeleteUser_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_delete_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.IdentityAsyncClient", - "shortName": "IdentityAsyncClient" - }, - "fullName": "google.showcase_v1beta1.IdentityAsyncClient.get_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.GetUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "GetUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.GetUserRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.User", - "shortName": "get_user" - }, - "description": "Sample for GetUser", - "file": "localhost:7469_v1beta1_generated_identity_get_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_GetUser_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": "localhost:7469_v1beta1_generated_identity_get_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.IdentityClient", - "shortName": "IdentityClient" - }, - "fullName": "google.showcase_v1beta1.IdentityClient.get_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.GetUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "GetUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.GetUserRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.User", - "shortName": "get_user" - }, - "description": "Sample for GetUser", - "file": "localhost:7469_v1beta1_generated_identity_get_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_GetUser_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": "localhost:7469_v1beta1_generated_identity_get_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.IdentityAsyncClient", - "shortName": "IdentityAsyncClient" - }, - "fullName": "google.showcase_v1beta1.IdentityAsyncClient.list_users", - "method": { - "fullName": "google.showcase.v1beta1.Identity.ListUsers", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "ListUsers" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ListUsersRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.identity.pagers.ListUsersAsyncPager", - "shortName": "list_users" - }, - "description": "Sample for ListUsers", - "file": "localhost:7469_v1beta1_generated_identity_list_users_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_ListUsers_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_list_users_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.IdentityClient", - "shortName": "IdentityClient" - }, - "fullName": "google.showcase_v1beta1.IdentityClient.list_users", - "method": { - "fullName": "google.showcase.v1beta1.Identity.ListUsers", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "ListUsers" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ListUsersRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.identity.pagers.ListUsersPager", - "shortName": "list_users" - }, - "description": "Sample for ListUsers", - "file": "localhost:7469_v1beta1_generated_identity_list_users_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_ListUsers_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_list_users_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.IdentityAsyncClient", - "shortName": "IdentityAsyncClient" - }, - "fullName": "google.showcase_v1beta1.IdentityAsyncClient.update_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.UpdateUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "UpdateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.UpdateUserRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.User", - "shortName": "update_user" - }, - "description": "Sample for UpdateUser", - "file": "localhost:7469_v1beta1_generated_identity_update_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_UpdateUser_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_update_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.IdentityClient", - "shortName": "IdentityClient" - }, - "fullName": "google.showcase_v1beta1.IdentityClient.update_user", - "method": { - "fullName": "google.showcase.v1beta1.Identity.UpdateUser", - "service": { - "fullName": "google.showcase.v1beta1.Identity", - "shortName": "Identity" - }, - "shortName": "UpdateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.UpdateUserRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.User", - "shortName": "update_user" - }, - "description": "Sample for UpdateUser", - "file": "localhost:7469_v1beta1_generated_identity_update_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Identity_UpdateUser_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_identity_update_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.connect", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.Connect", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "Connect" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.ConnectRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", - "shortName": "connect" - }, - "description": "Sample for Connect", - "file": "localhost:7469_v1beta1_generated_messaging_connect_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_Connect_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_connect_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.connect", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.Connect", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "Connect" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.ConnectRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", - "shortName": "connect" - }, - "description": "Sample for Connect", - "file": "localhost:7469_v1beta1_generated_messaging_connect_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_Connect_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_connect_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.create_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.CreateBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "CreateBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.CreateBlurbRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user", - "type": "str" - }, - { - "name": "text", - "type": "str" - }, - { - "name": "image", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Blurb", - "shortName": "create_blurb" - }, - "description": "Sample for CreateBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_create_blurb_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateBlurb_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": "localhost:7469_v1beta1_generated_messaging_create_blurb_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.create_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.CreateBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "CreateBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.CreateBlurbRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user", - "type": "str" - }, - { - "name": "text", - "type": "str" - }, - { - "name": "image", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Blurb", - "shortName": "create_blurb" - }, - "description": "Sample for CreateBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateBlurb_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": "localhost:7469_v1beta1_generated_messaging_create_blurb_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.create_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.CreateRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "CreateRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.CreateRoomRequest" - }, - { - "name": "display_name", - "type": "str" - }, - { - "name": "description", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Room", - "shortName": "create_room" - }, - "description": "Sample for CreateRoom", - "file": "localhost:7469_v1beta1_generated_messaging_create_room_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateRoom_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_create_room_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.create_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.CreateRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "CreateRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.CreateRoomRequest" - }, - { - "name": "display_name", - "type": "str" - }, - { - "name": "description", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Room", - "shortName": "create_room" - }, - "description": "Sample for CreateRoom", - "file": "localhost:7469_v1beta1_generated_messaging_create_room_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_CreateRoom_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_create_room_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.delete_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.DeleteBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "DeleteBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.DeleteBlurbRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_blurb" - }, - "description": "Sample for DeleteBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_delete_blurb_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.delete_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.DeleteBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "DeleteBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.DeleteBlurbRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_blurb" - }, - "description": "Sample for DeleteBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteBlurb_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_delete_blurb_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.delete_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.DeleteRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "DeleteRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.DeleteRoomRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_room" - }, - "description": "Sample for DeleteRoom", - "file": "localhost:7469_v1beta1_generated_messaging_delete_room_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteRoom_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_delete_room_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.delete_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.DeleteRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "DeleteRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.DeleteRoomRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_room" - }, - "description": "Sample for DeleteRoom", - "file": "localhost:7469_v1beta1_generated_messaging_delete_room_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_DeleteRoom_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_delete_room_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.get_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.GetBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "GetBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.GetBlurbRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Blurb", - "shortName": "get_blurb" - }, - "description": "Sample for GetBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_get_blurb_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetBlurb_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": "localhost:7469_v1beta1_generated_messaging_get_blurb_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.get_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.GetBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "GetBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.GetBlurbRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Blurb", - "shortName": "get_blurb" - }, - "description": "Sample for GetBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetBlurb_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": "localhost:7469_v1beta1_generated_messaging_get_blurb_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.get_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.GetRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "GetRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.GetRoomRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Room", - "shortName": "get_room" - }, - "description": "Sample for GetRoom", - "file": "localhost:7469_v1beta1_generated_messaging_get_room_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetRoom_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": "localhost:7469_v1beta1_generated_messaging_get_room_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.get_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.GetRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "GetRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.GetRoomRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Room", - "shortName": "get_room" - }, - "description": "Sample for GetRoom", - "file": "localhost:7469_v1beta1_generated_messaging_get_room_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_GetRoom_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": "localhost:7469_v1beta1_generated_messaging_get_room_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.list_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.ListBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "ListBlurbs" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ListBlurbsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListBlurbsAsyncPager", - "shortName": "list_blurbs" - }, - "description": "Sample for ListBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListBlurbs_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": "localhost:7469_v1beta1_generated_messaging_list_blurbs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.list_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.ListBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "ListBlurbs" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ListBlurbsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListBlurbsPager", - "shortName": "list_blurbs" - }, - "description": "Sample for ListBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListBlurbs_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": "localhost:7469_v1beta1_generated_messaging_list_blurbs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.list_rooms", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.ListRooms", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "ListRooms" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ListRoomsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListRoomsAsyncPager", - "shortName": "list_rooms" - }, - "description": "Sample for ListRooms", - "file": "localhost:7469_v1beta1_generated_messaging_list_rooms_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListRooms_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_list_rooms_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.list_rooms", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.ListRooms", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "ListRooms" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.ListRoomsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.services.messaging.pagers.ListRoomsPager", - "shortName": "list_rooms" - }, - "description": "Sample for ListRooms", - "file": "localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_ListRooms_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_list_rooms_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.search_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.SearchBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "SearchBlurbs" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.SearchBlurbsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "search_blurbs" - }, - "description": "Sample for SearchBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_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": "localhost:7469_v1beta1_generated_messaging_search_blurbs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.search_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.SearchBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "SearchBlurbs" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.SearchBlurbsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "search_blurbs" - }, - "description": "Sample for SearchBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_SearchBlurbs_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": "localhost:7469_v1beta1_generated_messaging_search_blurbs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.send_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.SendBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "SendBlurbs" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.CreateBlurbRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.SendBlurbsResponse", - "shortName": "send_blurbs" - }, - "description": "Sample for SendBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_SendBlurbs_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_send_blurbs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.send_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.SendBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "SendBlurbs" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.showcase_v1beta1.types.CreateBlurbRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.SendBlurbsResponse", - "shortName": "send_blurbs" - }, - "description": "Sample for SendBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_SendBlurbs_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_send_blurbs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.stream_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.StreamBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "StreamBlurbs" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.StreamBlurbsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", - "shortName": "stream_blurbs" - }, - "description": "Sample for StreamBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_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": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.stream_blurbs", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.StreamBlurbs", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "StreamBlurbs" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.StreamBlurbsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "Iterable[google.showcase_v1beta1.types.StreamBlurbsResponse]", - "shortName": "stream_blurbs" - }, - "description": "Sample for StreamBlurbs", - "file": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_StreamBlurbs_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": "localhost:7469_v1beta1_generated_messaging_stream_blurbs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.update_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.UpdateBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "UpdateBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.UpdateBlurbRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Blurb", - "shortName": "update_blurb" - }, - "description": "Sample for UpdateBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_update_blurb_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_update_blurb_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.update_blurb", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.UpdateBlurb", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "UpdateBlurb" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.UpdateBlurbRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Blurb", - "shortName": "update_blurb" - }, - "description": "Sample for UpdateBlurb", - "file": "localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateBlurb_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_update_blurb_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.showcase_v1beta1.MessagingAsyncClient", - "shortName": "MessagingAsyncClient" - }, - "fullName": "google.showcase_v1beta1.MessagingAsyncClient.update_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.UpdateRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "UpdateRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.UpdateRoomRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Room", - "shortName": "update_room" - }, - "description": "Sample for UpdateRoom", - "file": "localhost:7469_v1beta1_generated_messaging_update_room_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateRoom_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_update_room_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.showcase_v1beta1.MessagingClient", - "shortName": "MessagingClient" - }, - "fullName": "google.showcase_v1beta1.MessagingClient.update_room", - "method": { - "fullName": "google.showcase.v1beta1.Messaging.UpdateRoom", - "service": { - "fullName": "google.showcase.v1beta1.Messaging", - "shortName": "Messaging" - }, - "shortName": "UpdateRoom" - }, - "parameters": [ - { - "name": "request", - "type": "google.showcase_v1beta1.types.UpdateRoomRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.showcase_v1beta1.types.Room", - "shortName": "update_room" - }, - "description": "Sample for UpdateRoom", - "file": "localhost:7469_v1beta1_generated_messaging_update_room_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "localhost:7469_v1beta1_generated_Messaging_UpdateRoom_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "localhost:7469_v1beta1_generated_messaging_update_room_sync.py" - } - ] -} diff --git a/packages/gapic-generator/generated_showcase/setup.py b/packages/gapic-generator/generated_showcase/setup.py deleted file mode 100644 index b4f6da996141..000000000000 --- a/packages/gapic-generator/generated_showcase/setup.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-showcase' - - -description = "Google Showcase API client library" - -version = None - -with open(os.path.join(package_root, 'google/showcase/gapic_version.py')) as fp: - version_candidates = re.findall( - r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", - 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] >= 2.25.0, <3.0.0", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "grpcio >= 1.59.0, < 2.0.0", - "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", - "proto-plus >= 1.26.1, <2.0.0", - "protobuf >= 6.33.5, < 8.0.0", - "grpc-google-iam-v1 >= 0.14.2, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-showcase" - -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.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.14", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.10", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/packages/gapic-generator/generated_showcase/showcase.desc b/packages/gapic-generator/generated_showcase/showcase.desc deleted file mode 100644 index 319278acc51d374c112fa9cd0a2321ee18f4fce8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 260515 zcmd?S4U}D1b?2#f-+QIfEq#=pWLqxV_)@m9Bugb*HW=g>rzDl-GWzPO62ve@dR6sQ zD!Wv#Qm@Lg!0vQHpaZP5Cp2K1Bsk-c@R4pphmZ+P7D>bOB1{6^W_zbJa{p!-NT#4?zFzRJlE>%sASchefzf$6?KMGVT_k!UZpXT zUVCDE+xx^;T7)oCq0)S5osdU&BZ-1vQ%mhdK&b58FqW4ajkG$`TCz4b+_P>>1wC6>UfNMrRXwB7*q+uF z+MT5xweZkNjU8#vG%YW+cGSc3P;OkF))$&fQ|ET{gcn|H+@AJKEq9jM=Xdn-qHq5- zWn>((H-h_Qb7`ryI8X1PIzZJX+tU|!tXF$u_PcRix(WO&wC6jm)An+sz1$cd9^?Zs zx~(}qJ-YQ)nhWZCLr0W@wfEv6b-MR`=!S^6_1A^_h zp7G5&$L^T@KKMYod8&QBH0pyJY`~(Pla-eb2illv&o$>~hT4lW`(|46MqB&*6_nL6 zs%y^Ax0jk4SLcq>@4u~7o=j>-hEI;(`x~8feWSj4-M5lT`a89>vawO!ysokTU)Qoj z?S+ervoq(Gvi&#jzco8zw45D1dMHh^qq9>jFgl$r&ri1&v!!#bY|85rJv`M~SjuMSGjOml zH`|<_YGoH@m(E!)p^c$5yDzlRo?L2Dxk>efi&^_@xmwm-0$BZ>gJ2Hq+jrr@1(uxv zHMGt7Fgp8=jvg90K0dM+VEN$GJS(x2Ew+Aqd3KROPF~EK3xG1!oCLtR=7p@im^Eh> zTfAFp3)BmX5YPO~o~+Y8yL6$s*h;hM+0N49?Bw!N7nTD28KW&%08h>NY;bry8yz3a z4i1lxj_*mcmyJ%`bK=xQ_OjuzvEkzrqa)+liLva^iQ|VyCq_>kr*wBVeEh!bC8Ng= z@5x%=h`E3XK-(RGI4k_Mra{(tODN7~Cp*hql{*WqsoAr$Qw(Z;X1O`j%4XURLBEV8 zTWBqwpY3Q4I{-JGW^=RWX9F>n<~^U0v^T9JjcWh8ZTi*Qs5aJJn{G&x-fR7*KiszN z$LwKWqpF|&aQnJJdzdz=`soiZTesUD(vp7q!^_v*Xb&rms($*zE5hg3H>&#i$x52k z)-`HZuiI4__`OPYxOH}RzSXe--!n0B5=xmrJ3F(yXbZz|0rFW4nfNFqF_euisgekb zu`}?_5|ou@uZaBe{#UHQpYLZ5AgzGZi^8FBd>-1-Z%C7F#!eo}&bOA%wLvJf)1Gf> zrp~t)TbaQ&HZne8uz01;P|9DmwvGW`-McY;vXa(n>ymYiYL+}_;LVk6I6~*2cMr|B z6o6w>W+AoEfWrM_+P9mC1CUl~hPN>^W#zB#eM@or~w)4=PJ>}BU# z^8m6WxR(}}TYIuoV@EUbOa8am1Vu0zItSdzR%W{$HAeUP#yDN@k~EuYb|3-fpu=3S ziaV{D^R4+MW``Y!H!Nb7jqRgaLcWjg$u6*@U|l!tzk4wD!$N4CUCLVX+I(4DX*R(u zPq)rCm*9yP&!#H@%h6e> z3oShXWfdW5{qtf81n%6mJN@uDlwWD|d^lP6R8krEm*d%W*^DS|Vvzv>FJlMZm5&5# zGdtUAE-f=y@rFpVldYu-E#{!<-#AT*8wA2lS5j_ketMxjJHOPiHPjTD!0B2KwdUIJ z6GO@5^6cC+Ery9GtvgnPNVT)Pu+Uyy>SU8`Cfb0dk};tyE)Uv2)||hXbuM<6TIV}^ zn7^sHWsNU;h3{0U$h&j@PI3MYtbYdfxI8(;rc&M{i~VvJ4EGg>=Gx2C*+?8j@%5Bm z#2r~}DjYqSvssR&82N3VQ;nx)!y2I zd7Njf(ze5vX+-Bcs@NtgJ+-Coi=OI>7fY*tkKxQ%W^7C1T_C$o+xYild#+>9&|o0@ zDEH+(gE;U=$44pPOXXgs>zW%s$l0cB)dC)?LC>3;9DF z(%5zmqqf(4dIDU5K;nF^NgLu3MjY0j;qT!l=xH4QmHG>Ncy`PvOAO)F{vyj*blH*C zlD}!~EPjqTHSPjyut4_wouSUI;^Qo9FWAD_xnhcUWp|cq2?jKz1KHrdhi=*T>Unml zJHtpi`*uG%7=g*MN0Ed5?@|8|{t2~9pa%GgZX{YVGBr-`x7?BK+Xp|4R2&Hh#OrTG zvtekf8e3{Typ%Vl31g|Wmlu(~HCL?UygAJ$%ceCidDzIl5M9{woW6t90~Jle{4Z#F ztkxs;KF#*(?-Bby4Cu(nL?(RYn7U>Et+ze@1!uDC5ndK^rV)eM71aiJouT<*_JeK; zUr9+9&dsvc#A~E?Ot#TpB;1Rlx~LQ4Uq=5#KJ-;S3FijW2LDP%l+BvTL7SjtzU`G_ z$HqO<>~6Ny*8iAfYE+t|^VQ+k>DlQY5~YR)v+?E0V}aM_>ygFkblh2+m0ptMGvtA#7u*I3KQwDv=$+aAJG2&7t&T!y>cl^Y0v1`*0ekg0_t~ioA_dl-;$(?80?K9aUT6D#_Dv-3C@=pwu&9+``EtM8o{bfH}ns`&6!%UP;$Z(=gNXaBh0(Z9C#Wmt@{&A zYTWr<^m2V&5`$64TD&IT&!?l(OYf=Hfz)D5Atw6-3C$V^E2B(R+5)Ggl%Ge3(AKJ@ zjM1`_*%ziV1I5$G0w;$j4&AesG?2YI8dz%md#WXhOWMyVf;Fku5*{)%4E*>wJm*@|){Ej(| z{X?#}-QUMr3*bK8@`|EG5IcgzyFZ8=Y|THwa`^`!<`N07*mW^i&0|m3N*58YLAY2- zFs@5dm1d54S0?SHHcGqpUSkjW)`M9^S}oSKu$!+<*qB1-$th23M0Nq&)*iI2gr7lk zGArjI;x~$OTv!XTfMIi$rHwY6m;t|J=+XK_{yxuEvuwr!xR8y`G+B2Qh3$w<(j|`R z_WX^}v*7BYZ-izMS&}sj_1JVMHnXPoPE5W)T0%)&-)5IX!F1&KwuiL^kzSTh$!n+( zhI2>3nZh%ayOPcX6bxk}|D&k^g{~TS0^v8;Lp~a*Za|(vjTc$%mosoKL&d0{0R|tWC$u3JERX zeF&dXRBu8{{!O9!xX1_oVE;M$TcxrUzTXa3nb4F3C~407QHstM4zs62sCe(-?m<&a za#IROprsZ4f`xoT@;+CfFV6KP48(kM>-P^^8|x-?-3?!u=kgpIbPm?qliLN|TC=RZ z=sH&8$);T1(WKkChzR~Luk<$&pWca)aWETqS5_x`g`Dn_+5K4%Xz~|##yXOqi!ZWA zSJcelhs**(_26#%=jiCf$k^~v9=x=3BfZo7=Gu_*eEnm+CDItMIi2A_!CgL~&oo8{aHp4!}l8muIF88qfv7LG@vRhIS!k8R3; zkluVs4Ht;ZCIObwRCI{pc4`TURnlHJrh;K6J2Pkq8AQrkWQ(>ENEke0sx+=PGvMSi zU}%$z8TT>!BWNr6dV-H=iolKeC2TTSUYz5Vh8BqJ%q#Yu9{R^O?|o5o@2iIQzWjcC zP1^aoM{5f}US%T07OlB#x*beB7zh#3q(QoCcnAX@rly>7gu@Hj@dcH}haIaUCQ8S+$&+zQ+vYTTmJOtk7=!%dRO0 z3v|h+GP-uYwO!;%}gb`5EF5 z{(kDV2FZS3|}esZI6Y;Neqhvb0;l3KoP&8#c1Efk$T#cm&t~iPw?yjKKu!gWSki3uzu@o$nS~ z%$%9uat;s%%@~j8t_JN0B?J|Q?A&s<0#z0;BsR7PceM>AZUf!z#946LXV|0+L{07r zOQEKDjdWrX33TXd}mx{PKmZPYB7Oec#m7{dK*bhb(g+6(vg(A)#ji#YVq zEkno5M5n#0@Z-3AsE>jZy340pR=oGUy6h8@R|=VPTpj>fLBVZ@M;3o&@RkCIG&43Y zzzOZd5m7QDuNiJ4(ZHmkmAEou74WK!M^PvyUWITnQPnF9y|?Cbh$2X}r`u!fqp9}X z-pOS}opkn1x2HP$ys7IR=(Oi|X~JH1PVuEiyI_rBQi#_srrV=zZXMb`v_BgcQ)y-6=Is>a=p>wx-nE>Z(}XBoRo2 zG(CPgw}zKwj=9+f5pC~MJj--;<~kE?@2455*;AM#7M&-i$!1oc8F<35W^8D zb$SIh4VN9h3CjhY9%Ol7qXs$_eX+r$5Dgh|4yYV)&6<~3ze0(JF9hVLAi8@3F4}$( zf&d-e4BW!6&9dZXDS;uqX5OM$=LyAz*4koBFeGC{&BaBO7uji}f^I)cab0E$*X9IW zxb5~*HGMyfRudoYP=mzMN@VPYIL{u*T)eWNFSOnhROEzqc#j1+iFH8S}f#18X(ev+; z|oWLH4;?5m#HNu%}$0%dktwe17c)7nRb|4>n-kr2FlvEAh zk%C|;G~{4Z0fVL^7*)XdRMNL4jJj$aH@2k*4UAf&_UWW{`M_=6U>qJfIx;a*nggQ; z>n{f+@32OPG!i=`f|_Dqr0E(Rep)m=Y#mbfPm-6_0$+qq3+Y}C8NqQQ!&m^_y4!l0G4JOcUToO?j6P=ai{H`cb-~Fk| zrpCTvq0%l`i_*`8wn89Cp;zBCGR(OW8kS8EZo{61t)EXqC|}@1%kzcFN?_#d$hR}3 z?diQ!&BbY3(m{Ge_V;Z*3iJ*lA{%EDOaoNJp*nq8Yckt;&&08#yTUe6ERP;X&1C^` zJ>c;($>mqaB6$2va&4CWZ;r?HjoRmuq%rV8$D?`r1M7%v-|gTR&b8S^kYkoDrY{H$ zfFfks@(%TpAaD~HhUAab*j3qPolUi?RhO^A1|7JZOEE~tfxVTx$XgDkH)~xoiFRS* zB^SG3F;JlB?6}Tw7^u0g#D`^@GaGZzXE_^XwU*iod*>9OANgoLxVX7{996*TdT19k zM*hDZoPRFauqnO;=buaZx2FHXao*dg{dtmHJ@AGkJ7LkY%{eEEZtRCW`5B_$IHjHF z^Fh0slA9lMR;#MD~KnKToc_D*dp_0UH{%uO`Xffq%(~pZuhv6F@w!XcVIH#El#s*`0BD z4UvEZuEJK#?zgtT+UJ7i&ePmO$i$rCGp!uCS)ItwCpwf&)1F76mz5X`sgu%ltF<7V z%VmZQFlnIAi!9r(CY%KdZyEVllkGRgA|wB5vU^W@gtIJ3qvz|1&L$4LsMxyWaw)UE zJZ>PcM_Z=IW|IIRxk`K4*OT5W)BW(&L}Jxnix*sPEVUp;np~p+!O1sF7$5nBQKZGc zj+9Rku>V?=|9tC!m)}$eHx^34N&zQy6oB+TwBhqz>_Z#=H;X>B;eV4pCVPUG{70{^ zVpa1)#`XyPci(iYGqpIoz)9Y4-grw0SdTRZkEL7hMioAsR~+X=?+eqKtViJh^7YY# z8$TNA{^FzzHDmV0;OA@Uwl&`BXsa+AkGtwOr-3;lJN005rWH=S#$w|+X*!Ksfl(Z- zgoDLZj_{VAG;T__E-X)S2$N&ad9{>k^|5|`aX5e8xG~*wq1Ak_Tvdm8>tmbsxK!~_ zx-syE(^{RJUDomIY}M!sT=~fR!dDY~)EG`TwC0!3dkb}IVKx3nsIjt@UVRptSRZym zPD2ZX8&`oa?$*(jZN%>yhk)W?c1>xc9D!CNH>_&pZh7EVHc@=nctN_}gLOLL@b%Se zG%?q5X5JZ#l^dgJzYCM6bt>+(q}v@E?DY1vs~Q+LDfbZdMyWQo**}bBj)nKQ^0C8@ zYKPL`hkDX2D@x z`z5I#OSk0oa2lTxl`rZ4&d0ft|t89?hUBG zS~1qE2cipQ(6D8K=o7ZKysRV?2q-!qeA?8CkfCB@c=%GO8jWkyK3`R&h-f`*+_OIB z3vEwHB5bTZpT*I?j76gkNtz@ z+~98^(hC`lEotAxeJ4jwA3kyF;L(x(N@H`H+Jn1~o*16!PxA8U@rf7Q)?dv(IOPv& z?e=ipQj=XgbnNLi0d1NqHv!VStZL{P zGvn7((jAvV&YGw$SfZx0V2O7WYu+*V+%-{PlduwvgYT-Omyffp;r?EMqcvf8aoXeN zo*-7O-n)*O=Xgb1W8tgvZtt+J-t7Z4s~~-Sl3uoE<7)zXO`6WmV+MBFO9#o*6vNc*H~h0Yt#O*cN!e5iRkDpj7lsZY;N zx}HTR+pP*?Bof==ZEXY7HnCx>p?4?r>X0IF^``OsbenwAGs5fHOhUcg6 zp;F^Odbza%4ng2)QV>i%czSv1>2cxW>K+?iJuX~a`PuF1 z_Jwl`tH0Y_{;olll^@<ysTjq7l}+1YWeRjw&_ z%h=|rsS!IdK5XwudA7AZ`M{J@-k{A*cQDodOT^58@p&*{>TLremYQl zYsU><)t^fSvd3BxoeQ&Pmtu=ITD3lV7Fyex_6rlX6k@fVR&6uS%l#s_siszice=}} zZRBCm<8A5Xsswv%>M%*E_8zM(w8Jv&W$_hoE-p`A%n56+!>MPHw4OELeDFZJu}t@k z4XIN;0ts@~p%aHkPLGeid<0np(M&;@r^il_fa=&tf3+mo-&^Z_UjL1f8a8)pYKag6X(m0x4JKu&S!Z>gnpk+pb*6HRH zYpcV`7GKX>xq7}m9x4~x&v2;P=q6t={QSc*`669oyoY|57CnPp?^rJnMpXXqq9%dO zT7RAY*ZX_;e^38<{@>fbf&XvlPY2&rOE;Q|qlv?RFNJ7I+J|9u^Zx5rZBymiLx;4v z9q4g!dCb3*sfDHVAgkK&ITlKdBWceA9cx>=(dPZD)xfT{?;W?sH{3gZ`uK^lW5Y+s z!sm@E)7o6~RTsOrL3;$d*s`oJAUpeU+G=en&&}rI?NOR|rqf7|GVyh9R`%%Go5aC= zY2EPKNYjAf{&kJsw07vk*kP6wYsm3_`sC=yAy(Dk^V1$jnwDFRHa_xVP-<*3>g}mx z2S>*GlkTMlu?%)t$1<}-nt0YYMycz;->am3CCOZhD={SP3#Wi~jZt9YPSIqGx zq5JW4EB@W{3j`Qq=09!Tq8)?AWLBFcyLuQJExtP{f8~K~93eS&5_jkEL-(CNb^ImA zPrU5-SbwQ`tM)7|`;%$^N}w87q-%l2%HEc4Ievm&m92H;?z=}0O^mzcBp(EplkzHi zdo|s*hOrH{?_L#GyZ5f*`fGeMB&p*h7RoXERMHe!!bN&^7LCBQcvpnB6wgg-Z0t!J zgwt4NCye^hd?m%GhTA2)8J%CsYtOexYsQhlQf-;rs$>1}OO*PYkRmVJF-mTJ6Fw3_a{R~ zL;bP*%Yjc-(%$%(?b&m~s=4~Xq`%_%Vf7qoR9SxW=PGMnLs%hRnDYue>v)FVu`S{G zq3~GVG(x6l713DKwZy$+{qaR!`9OMQY**o6sASW{M{<&E7`q}=AjZqy$8QHeT}ii^ zLLucL_wgJ{(;`YdpldZLuljCiI8UZFR%&42e3}+-E{QhwDR(uQK5P3Fs=q&yMkoW$ zWNT)2K3JZ;!0v5^d?CjT`3L_oDqoSGH`>$=_7}qENy~b1Pvzx%gYUJJt2fr)CjpC4 zl*&;*ZrLpPF{1LZ{LjW{4=XGat;fViD@W%|AOg)!6b==>B(D25ft zGD{X9Dp>T@TB&gmez@8AO&{P%;;L-s+ zCH*C)M*m{GAdZ3rmL#jSpgH1J{jifC%+$#NMGldWS78c@P$;rx5bo;9oh`Cg@fb@n zDaLMMS<8TViqM$$j7TJln!z=qgLP_^SUqB(lxx_qV$l>R{EBlYcpzko)%lIQM}q#k z!O@ARx#sM7r2*ybEMvuugICLy7CTS+B;|GRAF<}NIar1VlE5s$v zPwxZ&ex49YL0HG0Q=r-=h_RKD9W%H2ppJ)(#2USrs{)Li7&D`-d5abEcZPR6> zE2U^v)@GP|Dbuk6ez7f?~MHu|0YW#rtqJabk~kyZSrje?B%ccIY0GLk}MuMNhxaK)HK# z;60pL+0hcK@l8s!)G zKy(A5`}TxJ$8mp9iJ@Cj*lEUI(h_wc0}-;P%|$Z9Us}ngpC5*5w$6Ddf70YLMU`BiUcmENWV*@3zC`7 zY?K_~hhIt~K<%}mfbr2lE<74Pb?Bae^PzPAe@?RDW%%vlf$Tv9i1z%Ch8>I@FWdPN zdz8HtvrKar%5R?m;6*G5c}Kg4D3uPsm7c04-hYQL}_I&G&vD+ zFXzXI3vbTD&f$~BX*#wD;Tgd;6!Mj_o@It+oy!_Tw3*n7hkcnn1b(k{jxaJ0d$QWJ zWoM>!B&GB?3sK)lI`f@5Nhaj0#g3_CzOb1l$Jxu_Q8p$r%lJM7q=dZDJ2{?9LEJm- zXmqTDh2M^M=rA>hf0WKx@o?lTCq??Mbvr`l@|)Hjj@i)l)6<#nS+^(VIM+{qxOd$x zF&nym`op1hx7))T8dd%Dhx^t&*B+7$T|fQd%|$MD{q%>ot-Ct?2@fqsYEsB=>lB!hOM5JUxSjHV7trCq)j#Rn94Q$I`j;aAnKGbD_QXU^cyM`F1AT z?Iq;*{1nFno~-?a>kd=~Ug^|vC&&aYy6h6^}7xOLH zC(lunO+#cAGpWCjK)^oY^emD3i;|r&4>=jjU(}Vc{6&4wiSJ0b{i18HizO0nzvy{4 zru!`4cJ0n}FRu(-2O&FY+Lp#;1yzH%Vl zZC&!}uH-p`*JMVrmcDV1WpNyuY%T&xYiSBl{mTk{+?DsCB;EkZ4 zxZh@dK;{RN=Mw*ToDtdX9;U+F3-zRE!1vm?p#2F|YpMOMjY1_(S0LwFFC_L{&h&U$`!Cfrz{ zc-tWk;9DdwvQZ9m%{q@$$FYX$ksM}DHB^sm%>v9EYN#H$?uPUQ1~V1!P4*11%^>X; z0pVrtY69ZQ>8jJ;y*ZBRr1-zLZy@x*sfOykSKSy(^mp&>n{3tTNJI4{$=>j)helqK zH$qH*^(A4|QISSoa;>jVN;LA4oA!i8);Fq0lcCVadKx*JH?p2aj`pF)+fpD#y?S(T zS1i%U(LH-ZBU~#sV^{KV(qe zbD-E|S9bFKH?RpsVM0eb2re1A(>$xBYm2S((q3%c$^L@|g$amm;pULI%>%>P`GcM)lLYjobF&daDd;+tqbmhn zr}`pCNkP}Cf!$#SQqXm3?@)Tbku3Lz+{XJ+pIHXaug^49g)&#EhGHBU-f0 zyb*QR49kI$i9o9;-jN_+H9XrHNFGq_RO z=-jgMm@)mE)Ajz6E@x^Ri!u{2vx&&8_@2gQw(Tg&bUbs_)p_H*K3BVn#z!7r-MFUb zT&ZzwtLI9MYl_ZoyF71PlXQ-m-V`8bnjWa_%U^4v9w;@Zsd`}3VDX;j9=L9IQKq>E zSV@j)`ku?@TpWEapDuCqxv(6QL>zr?z*!(A8kx)IoQm_wzA)$F=<|6a;^^}^;fSNp zXOT|D(dTnW;OGlUBnNTyg}f1Q^o1M}arA`&=kH0fo<lQ%1@15>VynZubCaBxEPa!2P=zvunK3W4l@!jU6xQb zjHs}b8V;3U!G7#UNhju-3xUl5D+5_huLx9w)YhmzbP1AlaqppgnqA;~D5n}1`5wwi zk}`OCC@0B^mh6Q~kR&fb_k~j9BFPJ-#s%qxoFu7F;}>$~!!~*`(W=uy8EvB%^O@5& zda=*BCGTkF;*~BHP@<8GNCiJ-GncTBK9bxpuv|=x?@khmWe>FM{o2mD=O<3jT2mqQ zZ-$jU?-nS198W9dG|?s>QJfLmz8}ef-vAaK$=R>A??-TV`Y^S9KQeedt4Lg@{uAq7 zSE(3t7hC&@-fPkmkYiOxjefF{92gjO-A1YiCpEEdNlJBBzH}6&U{K0Zw9xjyI+8-%wfKmyW|DU9+qGY=!g5hq9Y><}{yejLR9BU$7%09h}gOReF7) zHOm22y+ih5a&++n-za;AWR)#&eQT6nXmv~RfN}k71?S%8&@C1IS*3=vFMPqe(Syy! z1HSlY6^>C~2wzbCIldT}QA(Ta<+C#{hezQZMS>%{6KD9`p%&Q|%!*7Lx7>^ZMUoaO zoWdaLamp56O-dbjP5h`N@F;@^dP6Z77=n5(K;ys~4*)F=2I6@WILu)eZ{6( zNyCqWfi~arLmSMk`=9w>L>}~942H9VJSYtY;(u$Uc3D0c9lPd1fAN4X-df?{bsRn` z>+$jzI$+F$;)@=>c)a`tXN=zlC(WDG@mL;gDjx8~+bSFrjD2uI_Ft4ytaG3|C{WzX z7ym*i{%j=>3}->#Al%!G1^AFCqFU$uHUZPD{tp-_4=LXR5j>^_;>E3{av{8GaQo9^0#?jXN%+k5F z@sJ}PT|)JXxl3vAiOROi((6KleT~|aLhCk`+y(9H?A1C;M=H}|%^>@$RsmNZ%{(c% z;)HH&)PA{4G#mMX2gQVLqQ6ml7vmVbLJX$U z#g{O&l~6($gK8E7Bx;Zc3@|pewNZQbGiqupO;NLGYAa2>+i@kP&((InR!QEUGkr1F zU#qO&h+Rv=MC57I{uRR<7`P&e!m)m%g7gvI($;TO(EdUZ z=KLEKBrtD@mmjDkp8J5)&a^}^wxnalAE<;36TG#`TdxQ$=~(dxP+CJvK=_*lOz0LW z#+HhCX2T}wk!k08WioY#+<7X?%)gxwP!Li~lj2e6?l1( zq5XCx3hiu7*>XHjhRoK;A(Gq`tsRpAfH=oo#JX~?{BA+y+Qxsk zLVS)-5rQ?v=UkiqV?#Q1KUPVu9au1&=epR_;F*0&t^up=GL_}}_k=s-HYm~rni5A~ z3NoQG8b*4}DF*FW07Tf8$K_)M>=GzGR^cF^!>&9oAFEvRob>0MVj!Bc`a( z)lWEo=t+3>hI#Dh20t>vabcu#r7_3ycX6*JQ|O&Z?p)E(p}f9>m6;{kB-HH1TGO}%GSu1u~bmRYw;}~0>a-PYY2Z{@swo+htR5*W!AH$7*Ye*l;gz2 zH91+Mhb(4Hw$xbYFievTiWdey@PTH8C*=o0f|SJ*+Zgl% z;C|ptYl2D6p#fY2P*Vt}D5ycyCcYomOeb^c9BP7+WMn_rBFG3z(wcIYeerSbESAr^ z14GjOVJl~+-6I-6iiirRBOjW4wBQ9bAn(F^*oB!Pb{c>p;rPR>(zu=rPXu4gDVZS~ z9hq;%!DhnoGUH#QC0?tsh*G<`8gw+z669nV5eLy%=E6v20Wj7V_d}Zxc;L!ei$)yF zdWLcY>{ zhQ*~ik`!!_vX&L{q@bySp0!heELgi{-poO6_*8OU5eM4b{PbQTvOKSq}05zr5q6co&nry+-X0;{wa-xOY#w0Xg36tceY>tA&NF&TdoKGe%(xX$T z2;-#OP5W~O;H@k2!A2rB>}zDMIg@9-)P!(R$(+JOfIdtkG#r7B@BJN|GG&Rax4^ zZ0pido{IVaCAy~QT~nm%ry|>?$fr+59fcxYKNWS9x|D^#ifo$_Em4du;iRG%*fwvi za$wsOY3Z-Tw&iB)Y4rScW!?WwR;Vk>gYfx_d{rZn1o77uLM=3s9*yL0;z%gbKSl4K zA|v^mI1-9{`ZsYT6zTtO;z)Wll5bXUnrJ#G(Gtbjl1B2)O5b(ytyR8$S1i)fH!CeY=7K`PU_2_TcU6c}=B7aH%KQ1oWN2SHXKR^HA4|}tURgMcOz$=bUGH4OW8@j-l?HYV zrx3%Gq~=5je>bm?Ln@_}?jod8S|5uULVM(brWh0zia`2U0XBU&#j*5e6rbHWZKTA~>2n>Px3u(la<#KKinR22LhRi2V5hgy^Yh8NUjjRqcVS0!Ks0+mh?Ie!PkI$M zQ>*m~A-@n2LW#~Pdgl}w#xF#KP~_8JhzOxb=f4mU(ksY*F~M)CVNjwaim@fJ@n1~( zviR02KiAU~Qkj;1F~N7~FoBRK5`5R*k`O{Mwj_i+k>I@!Z)xd?1ow3)($W(N{_C4T z$c9GGFDL8%H3%8(LI_6|&b0}sk@(V$9O*Z|oZxO0ARC07cSht;0uYK02t|u8^TNRGK#S! z@v>h_aC`fw;$^>=Np2swJ>xi`AIoFII~&uYW4j?=Na-dv z*Xkl}xTwK95tE{wyvShQ7xN}>FedfBq(6cnCiT7q5W=^ZBHowW@Pb&xxbnW_=H~|h zY3coI0cfmJ-s}|shUa1OasXvMqn!w#%xCW}0F>DI{sKUm&)#1ESO>uO7Xa1)@cjbt z*Eh3j(nimpBUSKhWtyE--KR2>4! zmi!D{d1a*81G?ZG+hRLrgD=7v!Yu?id`0wZLQ!?)CWbkky+W+vX;*x1Z_o; z48fX(%UWhTX=`#Cqgx<0ae2k;0(Y%QIW#p@=At+utfV{wKn<-O0f5?Hm{=nQb_djy z+EQQx>%UYt#%Nqb`C&N0ir|6RGQ}#k(DbZsEe+hr3QlN*^rIN8=fVaeCtQd-3!2y@ zr2tz11=Y?Y+!Z>VN8>~w3kx>x{5kadu0(ag+Tuo!pcESavH27PChy9qh2LRnk=t_3 zG!R=aP(YGuL9F{}^#gI$RZM1cq3yGv_qrx7gb#J3nqx)hUWH}yV>5ullz|mvDFnML zw3%A#)aJ0G?9aN2L09FPcFUJoJkVGfU%7Qz{|)V$>XF!M9z$TX(jD)iIb*J-l>8cm zik@_+Ul(xhHsgourUKmV{g8z)hSHdyA<8l`aOidw#B#E=`bjd~ig^=GxSK2XJVTW15Ox0>ipjmxEW{M@}QIV#q}F zCrR%%k3CN%HGU>Zt{eC-x@LsEM1#GTDTm2evSx8Bu+JQDt!}5ZKbazLfCsB!@EpLN zxM#uwm=4 zn-|r|ViMplV0Xu&?V5j(SX}^N)W{TKjEWnPL&xJp5;{ymC*v} zN1RrEz!JoO?&pqVNZGlIP02I`-K=;)7Ec-Pu|pT9I`Ty(N6y*Vd6-zx=er?+A}vE% zTymZTPPQ1#IN}6;8!meVy=WkQCN9!QpbXY^so9)vJ=HNC>w-)BI_w$|Wvl=YXN?89 zACxm+;5^Qk?81m2+$YAr zqok>?bg<%k(OsGBu)4S7^%9q+J3p!s)|pf?CMr&{RI)EcB_TCq!k3bMHzrVIlE0KZ z&kYe2Q4+qC>^cyeLP_{ia@&j2T}A=a{fi_S;dI7?M6|#dG z{-OXv+T33x{d;3&Yxw5#iMxpkEBOMNQyn?l7|0=q5Vg) zBl$9kj4zxm7I`VJr2AO?$Sf?yX0F5Y2&Y9Ze=}LXEj^4Cn#Q#me=DhN9=t7YoUg)Z zQu|zDv!s7!2QA97GDNA`!`rMC21qj-%u;L*;DFysHg4i#4ey5v-(j^4^!S0#!F?7= zT;v%!;TKxvA)tXT`34iCqSdlEFD-e%qCKFi@8~j&*cIi!#LZiURO;92mUxIB&H*ZgDuNTtf1v7NWI{t zPcJXAIdxrSQ*JawWt3B07_#zICnk^Xl|r8BEOuEIiIBOg6hN2G5vy=k;+Q2)VcF@b z(NbiYrXhZXR0SJBe_2CT2+go(&HJ^bt6EtJOGzT|G%u2O^Zg;Nj6~rE{ z4e^kv&W2J9c0P(s-|MQ^J~#an2n9-DzTQ%0zyEi&Y}~H`w^^8-iZXOZ8)`8#$UrUa z;&Zs^mzy)KyRvN17WXUx4`KI4rjimO4|TZmiuf&9CGr*P5y4xR+h*JYh@Ti!g=`i~ z1)?|~6+NMlfLd%5(v`X;4*9vd!N_(>uNHoq#l1hSu_>c~ucz{$E=W+<)R|KBAnK<~ zH&OfuP)MyQ0>E{|sb#nFhLC5AQVDq!$u9`iIw>E~_L z-4SF`Ur~Jif%I!~Q=|!T`|qeG`v*Rcn?foWqMZcF5+UA2z8AB>XtRL=v^t2jMRSst zx&$d9q}zwuyIW+GQvFE9C7UgBI@B!5>LS%?EGSOukN8(k5@EOtOge7aP!no6)H;1f ztgi2gHso|sjDZGb!ct6y4LiB@6xWivQXkrMT|ni0vPPX3!RI>)eCm|KJF5L2i3*0m z=R2y`ct8k6@cE8vc1vsue7>W4)6Jv;5jr`)@MINd#E)m5t=Y9&na<>VveeB6n~>3_mauFp=-tdb zsi*_vU}h+r0naocDZ8al%6d{hAO$xVB7C0{D#Vm&3PCpTs(iSc7%o7?;cjBM?a=eV10?sLd7UK;By=@5LS2ainhxw6?ifh2%S8x6G!C>tSQh!PpEK zv=zbF3>fb%z|aAc_f{M3HcOMufbrfcDK9LvIZZfS^8TuaHW${OY+Px$m-AywR#UInUiF4NK^>%sb!2}p7Wm z)X_kvvVLF(fV>FozgfVp^FF^>&;s|nP=ppf;%khe?beggO|e%pBmSF7^74{x$F@98 zcd(Dd)=dh<&x4k8A6~R@Bv<60Z(QnFTB)1liO%30`vJL1G2H4D0?N)=RIOPw_C0o5 zNR78bUE&9{dpl!>k#;g&ZVNh69p~aud z?TbHvf0!M~l%^!dFV*G2;Nr6F4fLapIG%iO^N5qB3+4mHIBQFvTFjA#+fp_{oy(Cv zFS;@Dyz7{da|9?G1_5d3MHc<%qm0d4*1_ki{T}K@5eD)3Dxq$Y4k#jHf4&-QqZE;` zKVQW*`sd>OeKOE}v6|dH@PAga!|o??4I+pn?oc)GuqoLEAK73L`>=Bt@iXD(ju^iQ z9+l{J{w&(L)|VZR^xyy{MFY*_G|b=v;zYU}h%+bZdF4yUlcxni$WU_&R*w!T(C@&n zA{z$Qg0PsdT97f)$;AW}QbZL%a;PrgLLMnbn-{_37YjVfF8al4|GromJbtmd-&1pd zDDe2j>TM(OEqMH5^{&I|R~(P9slTiyw+#GWg<2a(1#*tc=?_`66)r<3-={hov{})e zqyOpD*%H}1S;_CifFmkp$^FX$l_IOZj2dm9`F;Mf%Gt{BEvWp<>a{n=BB=b!>h68c z)Y%)JswUfPZ|KwB@Km*Lqt~>(pXmxq(b*)6U2?NMt zC!eYo#rXD@dTfnA2tQLJd)d$RNRR{TzOBdk^_Ac4%`YT+E~R0q6B=S3!l;YOoQS2Y?p&M5Cu5{+F%jLyUi7_T{7%^dixon^ zs!7z?Zsysxb?Aw?2{xf%V2b8s?OW$0F=&l3Mltu8j}8f62roI-IIh-FL!D(T(zyf1 z0;f1zXUR7#ZiYrJx2nAT*z(o3PoqevKu093oH~wkYsP_?K{6OSR2BQS6ds`;=&G)y-(6Gvk}`OAO!G=y^+R-M51nE)(BdYQ5XjUzV$Fqr~vH*HEh8oY*q4ORplW ziT>QjCfdi0=-YT$zVIwohzOVX${0YabN}q0@>bb`l4Msb9AwFPnQ`-Yq6_V19mCEw zvgr7UhxOz}B2F?&9zm{U{YfNK0BpW|-6Nu|+Sn6ALSI26OK?kJb=+*W$RXAXts9X& zjl**kQ3s!pOn`}%$+o&oh#0}Ko}A{nKIV3MD^F;JDWQ#O zQ2t+PA)Awx`GN=T7`6vi1IO@ZoQin=?pkuyz#ljjN!e#Y!gNW+g;j;9Alp;(y@Zox zcm%}VjeVL0)hpr+bPXw2rdE-bI~$}EaxSXL+-s+&v)H!o)AVgw=yTvBmt&m35cnl5bw}?a+jAJUIqhH zro-gsMRQ}Qi^9Qu=SZ_2fjDsMjea1bAU->g5xF&Q4fXwgijgA3_ihp2+off1)J%S` zmfSk<#=0$Uzj!WAOf*x4BhL52(Z@|3aSXAvJ-)&$wVkk(f!}i{ScAoiBor^)7Gi@J zdS7rG7j0-|Ew#w5Otc)h$M{dHngKAnlUFaejez9vFZi{xRnm)2_{Cv$j+OcDYdT68 z2=}-7b#7+F%vldT5ZF>0k4M`?oyV|_tfiQ9_><)QSxZJGT^DT#5;~{Y!VnJA#BGf~ zD;lgh$n6;zG!BLGoSkdK>#%uxKzY$EqQ|)TT`%fwe%D--Dzh*Mi@fa8<7l~P#hI=M zCkhFrcY_|mJ!lv;HmL}96mDI?5qK{Ox&lPQtfvNu-6SXi&l#w*YqTGtidhAa9}`T4 zVunGBodRUgKG|ijxy`8X!Ai%OuJ}bM>$q^ZYG(+8%DJIY(Shz|37k=zHN=@0;i@03 zg$M*F7sCEvjZDDKMiq?q!5W7>LlLg}!P+$*7Di>b>IZ8(ZwXwLR93%LOMW-!s#+w! zRa?Kwl4fo6R93&u&OTuIw`_xoNYXfR?&^80sOix+_9ZLow`)Y->@r?yd8|IHrmi%L zd}(T&=3*$1z7-hMEgBQ!{cyQ4${$&?u@IV=(7}}3- zjxidhKKdeJmVyex<&d*;7YWGFMUZ~30DfR=nAr@%?OvfJtbC77?PUBgKp8#lM?&_D7>#q0z`Dbe5|EMD85v zkY+=xzWNB8(Yp^@WB^l}&r*EQUU9Wzb{S0S(wZ1T>4~ zR6`P(j&??U-73P8sP_=n;ZfsZ)ygEIocB6X;l_JQHWKvY?xmTe^N&SCqxW2xeecA~qwI?lw(xaLY32n*@u2pCQLv!Wm(eZA$#XJ~zbdk+mAr zupqG|v%JVXi$-@sj5oqdmf$d&O4qs%F$=!nopk78O?-nK9Y}=fXv#Ti1ar$UFpHIW z60Cr6Nl7aL+)8s3xn(yP)^xc2Yqy_Z*d4%7s-KwMB_P;Ljk_&ic{iesZgU5QHL7*< zrpV8LPisWDifo%|l=kBaMqAkj&1@3Zb>D2y1UmNtSS^m9`yD@z86& zqPQCB@QIz1`}W^*%ZqM)!7aDkx(oM>2jqw$&rZ86#3!~|Tr**qE_%p%!p52xQS(1n z$m6nge6AKU8*Vh~$>(ZhHVoe)wtTL3?OZ0v-Cy@L|>>89`s8UqA_5! zmXXk|Z^l>2;E8Z~MhFe@K{58ub~A|41bQ&X_GJSzN!q&!M+xD6>>}rIlDSUC^oKRn zBx8fr>6ov-D3jl&M$g~X*1e|g zo_B@0{hdsHGLdeQMd`agM9kA5n5RX@JVh}7-H3UL^#0w5d5U2EyAkt>$NQ=JvtuIN zB+UO*J(x%-0S86LJVo&JQ}tjX-Q4JTZGGL_0=^WF_u4w=H_w2t&BE8~>m;Kc^Eic) zPR#aiqB#Gu*>Elw>%FAp!W>E@ELUPE7E60r6jW0e`@@bx4H;OpyTZT&CelbfXmK30cM{>Oq(nwI{ou}O`>kKVC6ph(3yu&0U1Er;Yj zBQ9y~{2WJe1~blxBU!;7D{v&u`muUolHdd!Jys7)k|Lbwv3g*V6yZIO)nStIKWt{v z{apQf_#ZZF-ThoWI5Q~GRk;WqSy78?vvlw`*ME5a2O4DDv>3;&Y&UPN2e!srfO&I0 z_#Y@T?l;$i|3Oivk3UO`YqJ*D<8g6O0uGA4xF~{#$K&GK(&%}6eci8y#iiiPx7T}j zq<`E6CRs<7b_SeI@>28~!u*$J>Im5yc>L2F}DXa-Ud=%+?c;pecf; zCn7;pWMZF)1Wgfwej*YyMF{!{5wvJA0iFXAfVD>1Xa14o{TieTk9{-AVolZ zGSc7{M)fPt5)Ez<4gN}`K}x_u(P@w(H25o#2KyU5@2;==H-QEfWc%(qp=kd}rCDfBCG5J^>CDfBCG5Jb&hgqmGx_t z{nih0mC+!e(qaTvtL(SpD&wv77giZXK>e+_%K91Ahn}TX)~{9ep}5K@0S852WfWOu zABwANYoq6P>g)bfSY?Xl{+)X7W$Ay^D%+}6_HnH;V%J7xI7U$lCcS5Mk$E4__8JRT z!vFs*G3FJzWn!IfDME}Nk4uaqRPgb*#3(|yACF6nB1`P!afwl6iG5s4?5h$Ew#qyH zhxOz?)T?FI9Ee7_E%y4s^}S|{-wDq#>ns+)dnP7M$~;AY5Z5F4&gN$w2K-veFfE>?njS~$;2 zw;VTyPXvC&h(XsM*4JNQu6T-CHJ_~4t~Ou2m8rl3zn;b(umV3>Cwb)cIHdG|3ZJUi zb_{Me`y~mHvH}*560llc&F|8(2ek94`sG)ow}*Bp|NDAv+u)6*??WCz>~a>8;k@v#Til-(93Mu2zj)Ai(!>Yg5eG6ckfNI+tIpRR`tm%OF5PuH*Z z_z8*-(5LGm9|T1R=#T0>engET1oTJst=Aim-YRMQPk)F!ng#)t79*&V#{V?(Xx;+q zpGIk%BB1_h#~+4{P_u2%-W z!)^4rRX6vYYsV(_y+@Es*E1_GXIk6Zbcd!vfqI7Nou&5i(3*wZVkYN+S zLnoIV{2T;;Dn(lQ3Byk2m&&^f!{IBMJ#Zj2v2&NR3(TT^F9X9US3A^RxH!??xoel} z!JZk!7RM>hLE&m5x`5H2@G~WHKgkSmo&~Q%5jyDe**ZD2|3Gmx4P}}BLOuC&7~a3} zNE$n06a4sH`SrpO5xgvgqC1;GS_r<95wg>o2}uRy_?d1m?TsmRxDp7#jc;c=r}HR$ zSuV|-K`dA4>vEHLkc#R%2@`;y`u)bD5?HHp>vYk80=n!$IqFeI>qiI<*z@Y_72$$( zi;1~^59P_`A~&VKiks2}j6M4C<%e~JyAGer zecQ~2PLa00T;J~Q1&Xxv;rCT$JBxNhXYl#6HcQG!lPH^2AlVD*Ekq*%hsVHHb(=CfP1g+wNz?~iE z$M`L$`4DGA+8+3uKkOWJ6s-E~Ec1j?LVr)s_?N1dg2@Oxx z8}4_YGA%t-Cl!geMCq^UA=`2zk#mP)Y)PT9e^n2We!Qinzp8J&E?{4wv42%3+p@RB zr(dgwZ1W8Z9Hkgrl56B^1x#{{e61eNs8X4hzE+R`b-!Lu{6KIck$-?uCM!VJ(Yn6aFua=Q77a-EniOVE>4k5e#ug}GTlx~+9_F289{!pyV(T_PHIXV zHzAesxgboR`C(?9MQ<%#;0~#uZ95m%X~VyhJ>aLdLR{Ol0^id^ZsxD`vq2thN8eZ^ zeeu?XS-jOE@a`6QQ(|=PG1l=KoS+?CkkcKRftC0#&u3z%r|`D5=V8a@^(-S4maI*L zh%7%L?M^&hA3{5$hezbJ*U1{?!F-sYRs7rSDek_C(YJZ1ZV*vBL|YQfrjP@_C*B-G z94wQInQ%JA=G%uHwv$*eem=0_Z|j6(xQTXrIj=n?W{d5T_< zM)cz0qP20`aR=XR*KX>SI(@+3EB%N5(SNUer4;_Ay~?u5Dfb8eQqf5J$t zQ#&vx(P1vkr=Qy3jPyJoDq&A(DE?FId+O#D%{{Zb_$MPM@#a0*e*T}`Z&fE4(ghA5 ztR5J!AE1?CgxwGLG zJc}H#3_coGiRg`75tuLnC>~tVolg3l+(#W!tZBp0G7CYvEWJh4t_*NyLi7=lU<7h% zKT-g9h|u-pW-kBG_}!?6Igwi!qoRD(j)^nKrVQ`FY$vfGo!Lo3zZ9E80wK{$9^F$& zKE;~txY(zbe9<8NS`1u{E=Yq7(C7>4RJnG8BWN&huQQlMEUF<#q>y8Yi4^0&;)XKz zX2)WJ*4R8Il&Fh|%I&D0`icnkFjnHa6rmTfQ^KFjY48J&cYxV+5Fd%Ru#P<^b3S}a zIjYz{(e3$mhlnyx4^0wix~x>z#z9Pk0?=@Z=U^ zS`>PXs$_YF=u+!BVoA8u#qypzMMrKi1+ge~vRm+4SX9J0s<4i`7^Y-lXO!&gk=p&} zNf3^aK@j>7LR?g%h#>c#o*?&AL}GbQ&vuW7riiHao*u4YP~`76X_4>kN&c>(d-?5q@POQ}@TS0_t%BsAp&<60)@<&)m7R0nKFI*LY8Lf3WMkWT zJ8!}t6%Y?@&nsvHCWx~5qrxp|zTw4S$2G*^uFlzD!U@#iO37|BDC5>qvP!rtU4|U7 z>^6nbvSwC@+z$Wh#`kwOezz9#iciDp_Jg8odaX)BCV#Ag{T6FJ$~{qlw7Moi3O|uG z_{n@Dj^Yy1NN~oG10?z!rZUPlq4i}UG)_un!{P|PAM~-F%agB}&q<@80i&sI$*$Nd zcZQ5VI&BeHJXR;?@h;Rwu4NfBY;(%MI9>i`oYZa`G9v;+Ii0G7|sV-!>NdA%saSM2QCWGrHr zG`Q#?+@8Rkh$R*cVUE|Q-VRH2!V)sG0kSmh*ckj-N>UKzoOj5f7!QI?U1XBw#$<+I zK!U+Z+ndZijcO93MSHIs_a%SiG3&~ZZ-FZpLLvj=-BY7Kc&G8vPPzt2pV_)UrjLsv7#L zMW+(+YBVK{6(dv`T8ksrW}MeYc0#UH5U|XW5M540p;G~*fMN#At;Bwj%;_8;qX!*y zkWAR*#M;6++rRS)MsAKSML^5eobA;46p5FNfCzSVywu)hyd#_eh^qSTUWXwelh4Ia z%aB=}?*SSX@6bl5bjg-t%^Ww=ZI0ixGM>A55E?if7Di4d;=RbKGwiJslA!oc1Rsfj zw_GAiRwXz{B$3b*EJCfv?^!dhv1q8yiYD>UKIlXrSA*I?0dYCdrbK#$=GY3C2CrCJ z*?zB{4>in*je@~G-)Ciab`UY*!3cGZclE>#H9#MRjVa5RMo!+QrBEftJ_cc9C?g0< zU|y=c`xu#+nuew!et(eN-kkywi3joERCrX;zuO|vL;tKA=NN!}+aekc4eP2wPJ4&GsRY6nld9j2t}bp%l|KoHj^$Cc6qH zp_0~M2@b%}c>sE5=IA;vqLsdGecxsAEnvQG{pEfO9+jE1*RAIkJZYudrIr5E^~vMw zT`Q$b?SHyH-JU*Hf%YhCTyI#9i24&{rBvHlu1xyYuwvf2AaxdHLZd|)!@M|rY}+yo zMQOBKdKx+!tRh2hMKY>0fEX?iIicDE2=xu?gKTaO7{nXa2ie>nFz7d|53;#EK)!p! z`XHP81H`#EtVg~(5ynj$KfAtm{lHx-$1QsFWascU9nAC?^0mhw7=gNwTuO@t+>%Rw zc70$3R>S(-{{OM}Cg62l*L^SUy&wo2P!xD6QqW;0sW) z>?R~g03>7(Krl$A9KBbMaUDAzlR9HRJ9&MLoxH?poaDLA;0#UT*zHTxq_s1>wi#ZW zp(b4Ip+f4Ac<=Gy-)aT@$PfZ-h1t}*Is+=HSIgop-L`&|5ol*eKr6E zkRRIGe0zm(z)VA+$uLP?1hP0gD?J*drRb|vZP!R=I$9y5+p=_mR~tDqqFdv0z>AB~ za|XP)*oX2+7Z>}`)^HQBMkB8Ep{>|Ge?5{C558q<^R1OH;B3|iK4*_>2Hs$|BqA*L zRCAjL-cVq^2X?3lD9P-d;tNX%MM8tr{TxH(w)l+QrmmQ^y<9J6uPmoTJVM%MB zP7YT0YR)^utImDMBRY{vGcM7}6Fsokhyid$*PSj}XP|*}Px5K=(~%kpZ6E|HU!_`D zJS*D;haXhulw2thK10SaiNY^dJJ!?l?6c1@)dJK|Ht)k&=^3dF42@0tge0h%ZQUjJEV2n2Z zf#Nk6s-1lk)!Ia7wZCtoHo<}E$=c+JG2HB)?5o%NMki}S6VMu- z+Bf=C_3_&1AZi9|D9i;{4`6=Pb{{y`bQZDJIKfJl=kUgZ5e)_{bP50SD+SE^fcuS~$ce&(0(Wl`#J={)Ml6_O+ce!%5#TMA%mOGMdLw)s;r%v|`3=B<7 z;NRbtZ0Q>rKhf7wEVm}j{X>&|q|$Clio<>6-`<`igG1CG=u>N3`ro*b!Q`Ne45sUv z8O$San#fFk`etV)!&hP^y@y|6Ca*A)Yi1_C#LG>Ck!|RwKirwI4gK_oH)U)?KmFmZ zjBV(rKa5-lwxOSI=ddN;(n`~Cq4JD0wXj94Yzcv6L_)A0)2v-O}ky13Hg9dua-x`apUMjoxD%9f6#D{01^ z74~&o@y<#$=2%R(OMtOVM;2;D)osZZeNN@uij`P`yWK`;;0bGrS9ca~;*JN6Eo5kp z3XXO8<+_#N2X&d!L&Z(n(wulNXnJW%8B5it`2L;coyi-l7Yd!lj>_ZJamm4kz?co% z)LIwj$e6TXDi7`bbYki>bR>4Te1_~)+GovhX?YFOu^|f6bbII(x42R#SyO+mXx+l2 z_Z4?mezb_@aT(2EpXL6I!=w{Bur17YZ3G7Qq%g~_2@WKf0UG4nkk*DB5`}Ao{eTNC zvPIi%s9X~)xnmmXHfRLx@lfY|_Huvs0IXCzQs{ERvsU z4P`G{QpW-MW69^F3{*ZKpG$;k@TmOfn%NRK-iI&yA952GMO-?M6t`7=vl*+((uFCv zcSfX=P)+yxdd6{15NNd!GeQT-ZAj5*pv;2~AJI|d}tUF~Q7)B^@) z^xQ(M?sL*Pg6}BN^U4~B6b&r+PScX;2xFKYf)u7t7*(DXO)qlI+^iWlW}!*>pc&H9 zfY?yZF=;3gmQi-ae5exo%v>9iX#k9-(v%6AJZKBqVYIeMuCZuJ|C(Ph@~6TP#GX2^|?jyaqhx`yoBOy zTu8?AbLU-N3!!IJ2=|gO^Rwu4@o8Q=j~9c5o!QYfMT4z;%w?WY%9)N`dCcKXb33!} z%-r(gf?HLXXU%n>gf9Dx#OvyXo+T{j1)T7c@cTU#Tq-&!smFYXYpA50UNH^R5V8E=|XwVlvF z{mKO_SJR8n>Yz2v6q&ia+dL-ZzoJkDfYFuLiwhj%!krnNv3XJF_##r}V5U=Gm(KoGq40@fX?VQ-$N$Fum?8cj*XoN7G6n z`QkRyhuncaip54RAUt5YD|4o$)Zq1eo|27XO@fPiAQY>nE&9B+Gf`tgW zO;RSMM!;+n4iK46-coxJFC_JimV$e}NR4Ay(FVaim~cdM0niSrZ9Lzj?}0gRKm_*t zIks^y>2|I4KuB83aN()TphknTM`$xQA`s)mST)*WYc-VWo#7p8hekwFeW|2$gPL|2_#%{I zED}XAPt7R?ATG+^#BstV4j*S{B04@etD(G#dag)8nI?%G$095e5o3#YDl#P!Os6_| zqBc>T7&|_RMr#OFS9QET_5_aogVp}0csYb_Yy7EtZTQ4w^~Bi7;81-6{nnr~UX%4& z|EbBb`UF8xK})7L(tZuS0p-Sosm7!>L5q@8m>sCrMh8Yt4c1174^(NPIyyGV8Lf7* zhBAcAXa}s@jrF8jJ2_MzIDy`+ufH}@n|#VZIbNF_RcFV?>hks&@2gMN22PFi)rp6# z6Wcme)yM{G69XfCwUa}GYSW&ee&}p^#8evhaE#@r>m=@SooVZx<&u8-!@HYKMCFHm`onvg4n$3;e)_|E zo4V~GI#d1hhxcV_68-dtdz)TmU!wfb&+qEM(v0$BmW{9SA%z0PU6;)%=WV6Km(m?u zs_HJ!4W1ca;k?=BI@_6B5{|$e++a~b9I!2lY#QOxq5KQHizFDB*dS9BQL(s5DO{*# zem!!e4LO_Dpt4DF+j!uu|C#%2)F&7_S0I|eY!)-~~*Ph_UPrxav1Onb1QkuY9Ei<%^4*1~XG$MB?PP@81 z5hX$FR>|Bs##=*6u-v!IX*)nlzQ60x!2<^m9whTWp~GUIccp$m6oLy-_0TbS+u#>8 zlg*erALYR{d*#x~%-XcvJS?TY?T;xKZs^1bqr1D?{6%n9jv$(4F8?MS?{tv$Vm;q< z%XRYa9_MEj0k}EGFG}jMsW!v>D$mX@0bJs3y?mKgq3v z0ssOo_J1$}kemMAZ2GhLviZ-7_h*!W^z#C#U@%T`#7vy)b@an@#Wzj`n!kwRM;oWS zdVhxJ@JSe2HtDg7&qJ=l1}ezvG~ziAKm&@i3Y%g#o8Iih*W{-mH<$T78t5pis;;jz zgNL&jOmS@!$f06pl{MI{|4h%!+YzHW&VA961Rcq%Li)xJ_rmyA9>v}NA~}~)*F1XY zAZN}zeN!#=hVN3ttM22lC{d5~xp#GXpYfj8O|UheL??#a&x6_msr7l{CmnOROAA-Wv&0>Y)4i_nR53e$E{;rJ1V z2VYJZDCv-$ifikTRngF!aO@#|*%lK$ZPQ&wUg6r`BnK0Sj-4f!LzGa_d3c2ge^gYcX|mR|cO1$!7TPkUZwBIKt#wE8 zI;3{h&bn4Pm(3}_&Bl|#m>c=!o25;N%?uOD*HW5o?MQw@32V$U@igXyf5jEpCKaTJ z0o_7=>XRiRCY+B09J`{?cGuxUM-Lo*@BwXb`aiqtV)g!Y4>`hy{NUZyQBEYs)GC~p z)Y2jiol>PyGZVX7CD!4Ag94%lvgiCsfge2=migU#q_+l;RE6SP9C`jIns#ph1VCeVCrIKNCv9q)*GbS zQi=Im?%0v4wm$XILUOZfk<5aBj=KX0`$PO%UCi6=D_1u2U)?vTaup3)CxGlmenUJR z2`(5Deh0!z`CwAE5G^@Ro+i?L<@DO}oT<{<`ipxC^^WxIATLiX&y`Ok+c1xi@7<&y zsn<$-xA)#16-e?n8nBU$%$;3E9Wh1pVg!x1q&{$ViPZKqVvf&(e3R9lbD(}wYV0bZpT*pH%{_gw>F8&(VEgJYcFPzs{JSADymMFfxw*jB- zgBRPVZ}%#(tduKU*?QV6Dz?C80H>|q&cm8)j9ORsCp#K4P1tv{_FYHA3w?|SFbnN8 zlE5d2WnV z?0GZaZ124%KL-uVe=PTLy`gG(B(nH)2u$Dv`xvYvB&PZR|(S}$m_g~$C)j7srR{E2hHp9{jSsRssWLIb-9f%?0g*4I$ z@#Xi@mqIO_Cz2%FT3=F2KV3?;H}0(EO43R?9NZWdmjmla%i3?`V{&?V%@Twd8)@&o zH%~>4tr4ZNaK7$eBPwQva&NLr_gSA_T3oWET+@Etv{PnVeWzZI$9EQ_zrua5xZvj6 z7*5LJvNoETpC>$)xMu^pz4w*~lx;7v5XXa9y(3h@6JUN&RRm1d!0C`ahI`;`fW`Vw zy|gbwG8dIQ5o%$C7ie*zqf-9uyf-235WXRMny=PKhgDKDQtnV? z|92OXTQ0lJvp(+|z??QZd3vPQU&o+ydaOR&H(GmRpNu!_+?H`c9vB%rHHbIz)}+)o zIDs#6lC+GU7@HiMz#I9-q#ZlW(9q=RCu&1a;+DKEX`MJRHa?E&g^bSB86FzzXp#Ff zMw+2IeLOLAy06x;b^rNfPXmy-Q%iY&a_>4A2Zyj!jcx`a;0)tYf2zMD;pl$jc;CR| z7{gAV>>K5uddE%2UYB&ZaF{WPtHyMEd#f>#Ac&^?@6In6yhC4TrX?xAFPUe(Jw! z?{2Fn)O*6udi`_B`mmICpOo?7l+owMX@;p-0t>Hrkr651u$F8sZ`t1T$~3DvQ*`cFlt+}6}rNZ!@%;VF+5_gDT}{siVgq5abluj=w^J2PgG8mZ0q||cg-OVrCOpsO5$Pd{aivp>v*V$IWBMc_})|b2F$K(buBYJFHU8Ni9P)U+>&`b4h*S{LDP^;pXqPYz-RZbT3$L=9kARV zxC(kaA}YDP8z0pjXTio(1&6xCk~|psdZ|UrL-VV912bm>AT5&+l5L6mFdcR3#BpGC zkxNlK&2slVBY4tGA40sq&wRvmw5>+`%Y38BaUzGZ^liZ06dwD8N@8BJr|V|h$Gzm2 zsM?K(@{&x4UiHk|`A2&vaCc&!4cKZZ7|^n4*#sgCxg%TjpkLwMQg@(tKlbx$xUq(m z9C8PDDE3$T7=nmXbeBa{ideDzuc1}PY0O*hl#5 z8hV&8nv?P8_1#)KI;t*e@ZHHs3dKMyov#PphWoW%V(`EOb>czD*Xrs>> z3o~E=6lUG>IKbOt93XKHkHt7Z%nFZ@r`h5F*)|?SV;ExsAG>ECTZq{CK+|d=`2qn% za;ZI8yuI=h1tT!Yej-1aNu5|${FKf(EWJo-FpM5_(UODPzw7VBoQxOX_9;dY96y{8 zLu+u4#pvO%$r8>>qPBdM0mhfORydUCtC$3D-G*S6v&JZYrGc&Y_;2uVve@dsHORJI z{u|TE$vw9vKSR2Gc@Upt@IP9rj`bn8R$XqjfC|RtIKXJ<)|MAHmb^f$vHSy{%WAbV zdd@1yHyzxHM%N=D+C#9q$Z%zmS{p~~*`{QKhO#}WAq3(UFp1I!%&k^|#tlqdTNq@h z`FIgibG?Rh06!=HyDA>g7S3@-2j-19(5x%2D$Y9D2$)fybwyvD3$soRg3>u={X4fX z>-=6Jf%J#A7|9bt(7ixx0uo=kIjNXc;i&k=8Al_iB4;8wmJb2nE1TiCABN*0< zFBt@o#b?tt?IWU&Nb(VE{&M}lI3=DY+c{Aba!8FPR&R;GaN}7zJNvTCL#@2rxS7o_ zUNVnt-zXFt5L?NAY+lTmwO6x5T#HLnutI?o#=)8jr#<((m3ubP9~N&A?6z!*OP-uH zh(yGNcrulU3w2~Z(Qs4T!%XM^wV;SBIhJ?N&EZHro*b0DN#5Yq9JF>fjD((xOSDB* z{N61CPux8C6hbN8Z&$5&}r^sK78<@-a|5ZJTo`*tP^(NVv_J9J(r;8l|aur1gx~( zWL%8o_NA4ZtH}fI1^H~#|5B*PfjwjZ$OVVk;B{jFw>1ZO(035?j(E294rO==-Vx6g zk5t}PsE*8$^+}QenklGAL0U{;mN_Ifbu>DO6C#jeCk+eO5JxKO-qR~R7)e%o(uR64 z9L%f|U8+#6XdstE!*h(?P2zHBc&_c%SYrIoam{9U$D!sqvVPt`b`+c)TJ`c(y$bJ? zExlZNzIc@IPOXcaxj8uSh<40MMff3W+XN&h;q({-DxeILM(P^6eA-@wr&>eg>F7^RybO<9UaNiso_irh0K0)l%4I#@YIB4W$K(d~3V z)EHrZ-On8Aw1LK#a=gK4*gZAP3hl-{Y)VNX^%)~oZX?D<5)}s58jB45U4^!eSR{eU zy9zsRN**#q@bWzcVvzU8=w?o8xU5F*9^uW9lXj!)ji`DysuEaqjI+Tq%wGiYw?Iz<>zA@r?C&&?=Ihi?$4%HoCn>X{q5O2=>F_)*F1O+q`3MnjbdF7 z-J{%?*1+jd#iTRcN)ObEV`!y^@5;sihozW~fm?b%zR4J52D*F?ZS+8`IEFTQ_;@yk zHhTED#&F26l$4vlM@#LlMl1~@5v)@tr6W*S9Cfw@T1{yGdkW#g=|VA~{qHHF-wE^=>o^H59CCV>VDUx?601x z*TN17Q1D9yFW^@Q^Fq{9ko~4|h`mx!14&h*X+tM1uhN6=;I$MzQ~jfd9zOWc14r+b z*eQ|Z(L;wGICSXX;W!%QYXd;vivX9=e7exKI}Ba9+CE*l<+fzr2E!)tnF6PcuT8}& z4#x^0XS+w3Ut(k06yObllZi-Oa|_QPE-x-$atTUmDhZGgG;I)c7eNz6e5TOm`&ZF6 zh|d&muO>h0hz8QnYE}KSg0g4GpBORUkR+OB&lIAS*lJ#8Qa#h&9HbSIA>^c^M+m15 zx!BO_(GGX$%o0L^&PAd0688>7SwdCjQL$o4mzWtPjEhqXAcJdi@I_udmqQ9})FwAX zX@GGsOdyZL)IRjtLfg$@26Xe&XA70vlP7EjAjKaq6mP4XsN#2YV(lz)um0wx(U;FQLd7n6n~5ZbGLyuf+WSAh1aA1~~=HTjU^ znvXwUDE3s|UWj10)ak+{8b(LPz}VoBMc7Tmjd+^NP-LUNqz66%4~--aRa24=QPsND zysT%6L3)F)3qbRQY_N>I^?UFvMK~8n%q!@N4PRqTK0Hov2TdQn{;EbiC)l zD*Yr-if5br==w_2UCKm2AhUQ}Ce$fHi_H(-J6`S>q)=0s}Tmo$e8Xtcv z1i_FZK}ZJpQlZ@imts*ez?TZIIux)Y8Q@EWBM&MMk+?QOz%LiLD}J@=CSn2-&_mln z(oF;DX>Z+JU(>OX$y!-E+e6x!ne}H!ObZd>Hpm4aBDqMW_~k;|{s6ILieD~t9gGko zRQzh8cyKd_iO`*dT7#?J^#<4uxsLJ#hyfx(EGgwz3vF>{l$7$Tg#$fEa=L}C<;#Vp zzeY$|C&`&8zkbOFnLw=Z%Z1jPl8?*vza*jHceS^ExMb(y$a_ua%c|5q5B;gdZm4?k ztQ|>2MNji6dJl#S-bQSZP1zjF`^4p^Ol4+lVgG)q>-X=Ml1ZC}?01WvF(g_CAY5Cn zQA?3}XLhS=lE0pl^5x=~XnASs?q4m9`EW2Vf`#6P>V!rP9^&mVCWmYYH&=8n;V99vG=9Cn?E znIcGnIdYPq$PE5&q0MiRqzFm;Zh>s7KSGKlCX}~-DJk!NR|d==tJ;_YRUkH)K}kH< zXP3-Axmb3!F!U=)!DmS9i>^efA75NuO-K}LV zu)8lJP2|B8l*GYCj_g2MP9)EZdR<8(be#9Fjnq;lb~GqVQnKhCcP$W?@{;KbV(*id zBx=t$s}O98EZt)bCP%Mm%n-VPxkETEu23{O+U<;oB2@O563Oo{B14G%t3vVaN=J1< zLTe=QuuYeWx@wsZB8`eD|Eh4youMm~?-a>i+zS_LF1P$`q3Q48V%Me@(7{Hc)!!Cc zcN#R!;$eSxd1!bKG<@LDP^9+XMQA7j&EG|6wv=1mUTk_-aRW3s_HK}(0!x)(^!8$a zW{aSCXYsPQ;XTmsfkQ))+V3m|+)xCXcNW3TQE<~zZh23!=^KIOnl%nWkEEja6uBW& zlhq=C-g|j~cn?5)-~dsi_Io2h6anbH0!UlV)^f`?6`MW;Kj>M*KDzfDW zoUH=qgO>+~_khC(4h}_Xe=veW5pX^j@zYvv`Dn4}GaK>a9=(^FFbOUnjreI5K;LqC zfOro;eBc04r1rN&fG7gcw+Nu$li1TLQvc3k@&3xcD=661qXn}R;0>%04jlZGqbP{J zCDpy!K56GI?O4GCnq$9~DTsa3ycXi!a_rk;(%PL!_QZ_^dt<5<+tGFTm*ud^_;WW3 zg{Y>F+yPFZ?IGhE6ApJD##Y~z7$;a^pw2HS+PHW7E%6k=%6As`?N8oMx-+l>!}y+J z@j&J8a#%6NGKv(>zHh@(uNtl2Qm+6%Hf|2`0v^c2X(ram^wb%yGQJ+a!sbM6&;F9n z-|s^rxmgZ@Df;FSwskVebk}HRiD7^-lavA9RUH|@^m;?>An)LYohZ8X(*j}mEIy9N z6MqCB5qTn-?{N@ z@Tnr#KtFGUN!1@HazT(VGPm6&50~zSr=YF7wld#SPt#&yIx@@ecW948tMzvP`w2ORFtN~&+taVS&6dw8Px+GMUbJ$8i1EomJ* zd$?ZfY|p_X=Xz(SrVc%PXzJm!N2d-QJo|9(;fH%?XC6B8P;c*p51%`7QSZ{$zoboA>CqRok5TEc3buUaK2Q$y(fDBO@67^dpLQIuKQ3OzW6sq zZcuqkydoJzl?aE6l%_phD~CYbQD7quc}QX8cLB>w&%s{7Q4!X{Nllt&-HIUhlze2$ z#xWe~KAMAGntMQLOM#Ub!zGM<(~7|g^#4XH>P!G0N#@sz%?B&vhZBqyL(vXj#0{A(Uc$NM2K)= zld5GW(C{SK*zwVrStW-I8FOhR>sPv>ujHpvd*@d)l^@my)GkWE(Fz+NYa*r zX-fdgwIzVa7=F9hMp%v(i!sRGF5a{&`9*0<+J)IaE8-dO+2$)SGr_#MolBwu3hj*1 zB@LWT74iEOylqVtuA_Wl5$ZFT)_PLY+KOj+V7yUme_>iF z$6=~Wi<$;kw8{Zp&wF4SQJ>!0dBeYv}08ka_*zXWq+9-4qF!wMAFYy-x!Y8 z*hB{9(IaGg0nmpnH;Zx;MZ(j82wHMa0w~K!E4YeKWa<1_5myo4M|B|jdmV`0R!U`h zJiAFqhwUu&%XgJrWX{0^EfWB=lM3Sqp$&dnXtg(BIlit zhy(wC%Okcb1yI14-*2Iw#EMCRoSvHq3^^m<s#KM zrcXsE^W7yhefzB{FaJ@Al=-*C{Hz!Oa`#14Nvx2zB$DUjt-=v4;eAaJPlS7|B}(rr z6_d&yVh<3*`ldMnta8d;IKQu<74c*~+!9*RN_k(YwJi(K>hakSW zRJ^frV|C)fqNNdQsBEr73@}tC4>_OTuszvhm0=Da)991x@XTUEJ#z=j#@j-@k7>Ne zt)AS0N+hWw_p)DeD5XeW4K;6c7f;RYE8TG)dS+%So|+>#<`M+-0XjV0X_qk4*Fe5_ zApVn*!WAnAb$5i5THr4m$Tjcz_*$nn&HFzoZMi-9T0q7%uiX5J635c+g#uvGqW7n;>PEs!69-w@T9O zNWnpx8U9byjwKUmt#9*(PuMf^DBL7t5z{?=nhe@9F+GNv zxjJj>QfO=|Z?>E$)LWLUIdv7^(xT#^ODBr{_JJdMdq>i`6q{{RvnR+%zvK<`zW?TA zmzv%%z*Cbo)LL2&2o{qiOKnTOji)%}Duh#i| zzDawtDY-#{xCwZwk+!=1F83#`VZbp<$hD3*t=IW|t;zOmNFq@u2Y2xZ6u)(r4G8i} zNeJ2!ax&U75@Kr<)s=X&0}`6BV)^zYnLWK?>5BtN-dJy&od^%Sw>7URvb=$sr@ZE^ zN!u*BCf+hLO+^vr)_UvgaWAK!KzpLhb<`|S0#%j+C=hxM6kduZJ5o^MIuIzl)FNvR zpztaKg?H_|Yl)!5dSU%+<6Un3*kYWWUz}Rqa|3T!AG60*D(^~KW>248T%6yto#(Cf zEwlX;d{lPd>7E;TzK!qub^B>~T)2=6()8lRJ<6Z9z4!1nkeVj6dt`2Q=5enI)Ztfo zNPOZPIWedAbkJUV?}2MMON9;jsp?T9mNU2=NK^9ZJ}%cUVhGC@h%gxEoMt0#;;OpO*#HKvMmwAA_EZrR|>@UB+kd(bn1fqsCe*FQt*8r(@?%50w9RQBGME|xza$^S1 z>(>ZZy#B!4Zou4J-nAYWv$9C_?9V_qPL_`UQ8z#71C21nh7I?a#uXh3-nd#`z8o&swYi~B$Mu!_vNo({ zzE@Gq9gSF>Tqd3qS@Gq=?yMpAO!;dsH{LLw4dYyghltz#&l@I*`Y^yFM$1_5c4T7{ zn;KtRz5c|~X~Vg#a`U?37^fmtx|kIgQtw;`ifj_sADFuhm^*rJ*%TP{DRADBY#p9i z)xK1|rfsW|rm4Nm<`$TC)q1a#GhTTv-Oqbw)ZN!7i7Pj(^J{DN1@@lf)a!b$?D#_8 z_W4EpK9nTn*n>wNc)0)Tl3V%easnV%-yPXh(H0Et5gk3Qx9LHhX@0?9E#5M0QNzcM zO$7DTv13oTR_b;CX2i3ty{}kEejIO#ZROH-F1-68xj)AX&fA@lpi7Hub_JQz1fWnykB7l>RyQKd zyhT}nbd`6xJ*-iM1+Fm6GnKDQ%McurQ zW2I+=tE@&RUP-t1lG3dyof_9wcQoB=nbio{-@(;VWI-bX!_KB^$cMJ8>2bSxs=Zv& zPfwDzyXlBMq>g_2!^$NYt$|PRvO>o^PwxBYcj8#G|xfn-b6DFY^SV%)5P(a7sEjPsylzjKD z&R7CHcXvG^LyEq{Kz2{_-j-xX(q_dU{KDrt!=qpJabaiZE*>sbemaecwq$eHXJGO? zTUnVpKhq_e$^tnw=xkioah!$vYU5ppdLJYm3{gb*mPX6@0lV2_*@SkOd&qAWt~0Y- zJ;tZGSUklKii1*j%btJ{t@Q3&?u{kz(|zc*0Y9YoXzpq5jrb`vJAUlZyBt3lULGty zQmQ10r3-x7<_UC>yI z=elRQnQh-3#gOpB?m0WP-1Amafj!^ZkR+qi9zLqK`=9UJ=V>2BM98vmqbuMI`*G>9 zmP)`Iw&K!bx9*K4@b=i@zJNEm9QQR3M7)&(-t5t^u>d|8E{>Ke4_7DT21U1-$eNuc zok@nPZ*0&};7%tKqjYJw<+cEZt`Q%;eSa(g)bP=P0F<1GPc)y5Ks5)T?9t-}6ejG~ z7f+Qck6t@a@gN}VnWugV7s#&)py=N1*Wc3{O91xzM;{M>$-lSWJQ)Go5&*MD zPZ?mC$KO!=nv!MZfi+(%!&FK$-%4hD{~71zORt=QiG98FhL)QHV3^lSZ`gBBECJ>l z4!$OU*#ekPHUEPMW=jCm9=*xH#2SC5I8&;ed|~T*Bba@Y+^o3{P)zitGcC6S(3Fer zOy#~<0?;$Pj|D)t0_arpbOdy30Ms7+C5~+@bApjC7Qe1k`Mu@_P@{p1joLO^*4R9* z>&zu|NeWWuCiD3~1SE-}-NLgv8Q@VLgLlLVcliDVoW;;(SG<>neuB{RgLc4AnZ@2|^ z&;Vm0j~V&*ml1`LqzN*T1SnxHPDrkzWq&mpq`Lu?iBq0DTTGZmAdJ(O?+ebkc9D(D zuk@qj^kr3qW+z#tO(50Z+6v#DXGWNYDSTK=v9On2Oe+vaawo$e^jiK6E`{Z4+QkEM zP4UL36;BPVWRo}qIo3nRkNCCS3V!wFEApOMUgrL6n5MG}5s2J!J+4eZ{*NbZ+;OJn zkvG@Q+rV&WzrM6fSV-woOGn_iZP4ze9k<64w0mjqkwCj`(C%~1Umt0=Ezqt#+D7CB z{(x^QG<|acb0rZTNZ?A#CUMO3>NUR|F;h(`IUQRvMR!*=X`N!5JCRaE_Yez zL+>aQJ$p-&Mc`5F2rVJV@^**El<}6T?7u z(aA3-&3SqVi(C(PP;mdT#-L*B*)Qi1gQi_?~N%>=oFCNTPS-_BSiyZ-~Gvyfkf4BD&U&OmGBCJ<`6jR3FHyB7S|aQ1pyNO+_VHp%`gW4vHTv1Q&YVQuTuc zTO+R8EK=F6{8&r6wg_rAX=mZwZm*BUww@A1KC_ zT50JcSxf9Q6w{X2S}3M1v2lEqe18EZtyYS$CFKP9Xg0?R2K#6M&j`nsSly9~TIP61e8(NHVyX>rQc56n$#kNAY8Y4$nYDkybxesN5>2PO8!n z+1hTwsdJK5wvL!H8AEwouRy)D!%%3*CyJuAOGZ!)g(97PyH?O=LrSxc7n;7CIQvf( za_R^3y2|zz-Suf{V#9h08=GCf8oW!{CZhAXrAgv`O!$VM&_(f#DAR7(qLU^oTMILD z%hmI2IbExZU3RR`>7ZB%QLAN%HCPDZphDQk3$2pjLn5*xMW0@ZOvEP& z?J>obnC~YFx5k_`nut#n?z%hqKH-E6D*vp|^nKvuJM%a(w=ww0!nvuX6}zJcS8Jk^ za5K{pRNG~Sp7kU4d>2Z!pxiu>ElIFYgc6v(hy$DrPHlx0nIE18Yeb3lLD3ON5u*BJ zTptwa^^=9N^9G6_@RNmGbVgRT5q6bNkxS5~f)XuJj4dgU=~IPvU+%o6rB4-Zc~$(F zmOfRu`yP~YmIdMm3r)YxOgxpN9@CA%(NoQk3w}bT7^{va>nRANk~?Y+?|FqRcz!Zd zQ3fQ6h5n!x@pj;6V=1?gx$XaCg=@`F=JlsZh|cR473IwQLxtv7S?HCO`G5x=BxMgk z!4DPgtfn>i;GY+oZ%%6nfjlT@52*3a3%dk@_d)rG3(Z{VLrk5T6ry;rJ$qnZ?8u-3 zb)P9T??^uoY4BiM_JA6nDcsnR_QA~jNWMwofd?M>rcUMT{v(BLH>5QngC8w4cce{f z2jM|`_JA5cTG)PLT7&8Su{>1TICzjjCExZR6I3D|GH;ZdKNoi$N_0rkDVQRaKNoi$ ziVXR4an~`1@Dp*bqeNATzSmKt>QBVIjv`fmBJOp~BH5qJdX*4DG4?9d|76yy#EzfL zdZqMJQT}SSq;nLV+9^`?rwZ*Ze^IoLk-vPb;QyzyUbU}NjJ;|yemd(FzCG`<~O`be0NE6LP_Vs_6 z0j!OjVgy(l`M=Bn)<*s>Gl1F1e?CK#c5aFhP1?DCK0}js?w^;K>S$u;{>4Jkx6S6F zwrYy8S8dh5nDwfy`WFi~`F`A7BzxBv*i-`|lt+tVM3bVdx!xe6NqMxsP}nW4uL!Zd z-2BC?*LJE>jJ+xX`iohw?Nt3@*6TKcTVvLo=HfQ0Qj8ehM%6E67~V$JFBQ0p(tEw3 z-2AT##R$?3RHf+BaC7kns{ZT3RzC<(r0Tyebd*EY?UvRolG=8vlI1M+x}B=Oob|e$ zs=u7|dSkiySE7{FT)Ytqp%}Zlk*dE^*dFnJBUOK;P;mjRx!7T;$?ggm?w~4}$|4Z> zLs8uAf*{{g^;ZkkPC{vg;T_64R;>2!2=SW4sJe1KlEn@d2w$W{hVD$y``Py=3fWQ(9%v? zq8MA+NlU+;!L*Z>em#R}CoTPY2GdRD=HH0YVRP{&TA~%YKktj@{+2*U$~X4oe@eX zQuX%>_sA;MOp$N@Af9e00R%;#Mv6522a!lA($XJ9BBe-6f8eJZwFHm8o+!P^6`=#uL{Tshj^WgGpyMim@f_0DqXlq#fW7Gnljk{9y(YJHQ`B z*>p=$XE%zmC2a_Q6c-L}Y3YyR!l6h@e-vfYE!q(NI2)bPKU0jeqYdGYv)R#x@WxZe<^I)uCXX;R2kj;Fsu^I zP&Cq4kv{)Qr(ge;mwz3$99{}qiUz!jeEZi0VmAF-O8+(F1m~r|qiCDDiuM+f)xQPU zzX|FvUTWo1wE0$%Z~sQZs(;Ij{%!WHmMX>gtwiC!&AtUi|1E=8Ym;JxS7Dz2&Ed85 zXm2Yvy%SF)om#bG-ln{8@01445}&<;%q^8?bUgsap%nkijgg-s$@JTg_Z zE>nuegWS`YGt=!W!Ms9~=00WCm7r1r3Wft1KI5KV?H$FfE`@k{wRaRvek?YVUhUn* zCOKAVI9j&vR@NNdCSY09-cu}AxJ^Jhj5Nbp{=gdnU9VJMZ*B60<%!m4(}fXFwDz9j zb{8-_(b{{8NQy_Sf1vqB^?$GR?|G)&Xe13p&}znfMq%`xwTx=c1w3onHx{?WF0@p> zkuK7}$=|yxxigoq#e?HxR`d`rnfM2IWzAJ$<_5z%$xnN@UxW-fOQdV|ulN55C(Yw? zGxO8^;btGg7AnVULnDKy`-e{SJy9F0uk$!3_+)HcH`exzAY)Og554|Wtv)n}(>b@& zj-8ss=y`fyuI))u8%@j2azn43Jb7xeuYW{=ESw-ujgHj^hp5i2xD%5Ial4Wo zqg;nObaH(1sndf)$NNr=Om=LwmIm>EuK`@WqxINyvb}Nm<=dm5UmR_>4a~FsuI%{^ z-7LF3yN($A_y=+1{l$)^`VH1-`e-THj)o*QOqKp}1GdJm`)#d%bEkHO?M>%jxvcdS z@4=VkJ?MUd9ZfsUc@RIsGB>okBj8O(N)sOok!*#!9%;&w>@I zW(azej4p55m|rAzsQa%XJNp{Dh;u@>PLeTB|GkFFIqv8612c|brgxuLS6AoNpnKC^ z1*D9HZr%XyH-goq2{|#l`$5r9&N%Phw8R+kOq?UXYCseYSG#`Ww zR(`Ws?OR~3$zC|c#wCi;mKx{GDd;?TC>8?w>^1GSXJ`r8X}BFun;azLra94+$S3Nw z&Dq1-z{nA3P01EKgQZTPPs@1{Uj?#;`(2uiU`68Ob_zTjqyS#Q zB2HGL*+*mQ;#{kuc`TE?2BK8x_)oT`EWZ zWkF_g*#7;r0A#^rYL|}&lX)PBE!7XK7RDf{GTJ7aZkX}^ZcAW?7 z)UvjD_BF$<+(~fDSu|&j=x|PBIQ*#rn(IaU4kc!_7mf7Ckvndn7Oz`R5w=7niu~ zmDeN(C3V;G;u4;HW(szQIRpS>91UlH(t~79`6-8=(yM|0hYENl`RwIDjtnc3Ng&(k zks-ph0YE>>=c$bIxipuIS)L$~!~=E8(EyT|B?5*Slj&+2>oHz4vXO^OySPuuW1_lu zZN*d8ovDpJL9pN8>Aw2#sgnp!XXFp;!_ySJIvpOzmeQ*k-hcDqu{Qh3O7ovL9bS$L zUv-3_7tDJ8PFrg3XM)>{Ev$TAb!J7&Q??_905>=Rjop) z6Nj;Ge76J7b%i6vj>6;kY?H zvwWbz>sO!KV`~Tw$;P#ek3O7KF5+=za4AH%yj#!R|4F?-n_gQWv95F2W2eUnImH-S z9I#?;LP8N3t8>xd+Z!S z;xB_i&#)|8sNJlr74N%~w-#E-Ep0KhTzCFKbkK|*n+iT4*O(f$SAllyMq4q+XURIJ z`&%Q>-UDMt7E(s-G$<;E8-ivsG}!W=7KE`RKPTu5aedD+70wu^!kT)-jJ zBIj3?&k;UhdmB+6YcNfV5n)v+2j!f*838{Adr7=!!Z?E4Y=i*pxUi5)QK7Mj<*cpr zmKo-B(Ovb#Ol^e9pam!k?tm4-CA@7IgO5qcR2`R0T2^t9Wxs$dL;A4HJnr8`m@u5L zcl!-HqL@AuJj0EYb}<$B-D|hRX><1se8HO;mI)S2?u(LvG1;{RD2rnS9+=1#s&;B= zT0*`%K}%H2%ZmGOYUE~LE+)afWHx-1B`MD(%tVqT2BdnXmMSaGn$5TT>AIk)(z3;yP!k5VrT;mQ!!I zMns==AGdGFg<=1a8>z*g;CfL$K2|^3w>}jC*-9+?B3hx=q`5Z!#1S+?{_6o$L2xKN zJB>n#e;?>*KK3N3g9MeOcf6YV=8J#&*Y7P@7K>e*!b_%~IKuw<4O*M+>F~#|yT;~Q zZ+4B%=qnnVS2Q;NGiYpjGL22oi_qBITS(p=G&c8;r1QTPt94yJu)-~Q>`~{Wy$L#G zJ9_(t=(hNf?Jgm)n#4m=SH9Kl4%|w?ZnLRQCa`m|o?cG5BAypBzw(VS7*~RL9)aqj z_{Y*|E+}MgS>co3%@jQAnh_&vXa(~|V=ITRt(6BFT5+v^V?#%(Z*rx|MxDwgKt=AT zDw}Fo5P|Q(F*a&c?z#C@{+mcUg@R4(oaSvV2f>&FKqf|3O)z0spKGc#n<<=Jyb4)yjr2E82}0?s1LaICq=Eg;XiuqVlpDC)_DA-u~W!!-Gd2 zeE3Ybiw4=Up+~CE9(i!;9JdTm{oJ{H^_hdcXM4{bo>ui7a-~o?ig#Z`u2d>Vv6OO5 z@wuY>Nb?PqKP4J~sGsEpPM5Y*OTF{Vkn{6r0eQ13?Uf|P>?4|N}8#(EDQ?ml?rU=Dq0 z^Ae%Y9O@1q@l6g#(#ky2+?wJ@dYMPCJpV?-ku)>l=!?b8aP+_xaMXL`frBpqN&0+K zEHzL8ddADqot+8-?sReyXO^%%OX~DRt_MBOeHU8fM;|`g`vTz7=fIVxX+L=QT%PG= z0*)OV?0@Lk!DGkr=x>DEzneb$(6M8A^qb-*hkh*drGC)=d0i7B1|j87^RCLL3sOhd z$Sn}I98m`}!!ZX!WxYM~K;(wD?)^%Vl#@vz$O#!G9no4Io)>w8QfkjFbXO;4JlqY` zT?EN!0{n(m?OJwtk^HQ!m18!1S7At6`qSwuH6Bkj{JHV*&XJhuhw!0|%g{7LXbbQ@ zH{aoM=_COp-*xT0okLhu)9Ktz`j0s!bAaCcR&r@B?M6*KBI-<9lBdyoQtKQg4Nhlm z4z+&6qxKMnWDi}WuyYvAqz6)l!%<%BoxSiRjt`;4>N(jae+qlYS~*$XnVzTq?P9Vg zcb>v^Uf$X-#$w+2#-zRO)$42XGv&vVa%hb^G-KpD=~I<0w&7$IDvigF>N`Tc^vO!+ z$)scbXSio>F-(NSi(XKQVTEU(j!{RJu(hqeO%Er-z2L_tNn_`rmhXs%CObds9@LYT z)gfBPKTU20J6+uzKa?gT0HcAD+|HZoe|p2|YFh;Qx}U8+I`7$ZzF2zYaP`XJ>VJmA zRabVn>Ut4}tJ@1??>B4sZA1@}`X64OTV*ge6Ybf1DqHXN->|vcxL_-a{I}gw_200# z+wQtQ`K3{l`CHyyYWgNp=6`N9n$?05HY{6&7#M31|4j)TG=4~T78X9G8&iDe7E2CC zGt+jftjgL^VsjUekfgWAkTp6sIdlw5Rv!X=)TGB9z>gctFc9rk+NX@ScQ)J>-s!q- z25+KS5LgxOtM5(w8!p%(2AT5#0Z$$|jSR&hUYYr0zOs-A)K zKCL@6dR`rVy{5-B`8=?HUvuWF-xF@lf$Q81RpQU9G~zef_q^KweNE4EM1fIT|6I0a zI9VG|cAvEl=a~Al(U_gtrLK6O!mjT7gYDngV~_=G@*xrb0}HiP?3D{L0R@ftHQ-E1 z%p7O>g{oj3o~97i&rh909Zt&u}c15%FjiA3yC*5NUT90x4=97b!%^N z$OYG=7H2@UFG7>8uo;=erzk%JsEZgo=eXjjN_wa+pQ)uO(ph#_hd7>I(qqYH)A1Z6 znT%;!;sA+M))iuc-5~k&q8-Io7rFI8Vs1Kj;mFU?hvp7FYTX>Vm*2hqyBGPIvx+UD zb&I-Iow`_Ec{4e)bj;EkYv@`JB?n?2oM!FKttvrM)FI(Dqu)9@Tg+WFzo&kj(MrH! zOFlznC-tbvMzkfU1A-+IJAh7o0t4u)a0L7vLM0bN#SH{PrssGW)aPmZTit_hA=_WR#xhijV#N6 zuyTpiAa9AsR$D+E?~FZY4UP663+AD?#?rYP%XzT{$ijeY$)P!myf-jJ`TDmK6 zsOsS<9!&CquYCI~$WrmNb^SO&wu_u0VahCc0aMS;%+Gg8;Nncb*Ekcistu;gu1bq! z0!wjB%PH-J5NOtEN^+YJXZDp?gYR$q)9q}fXMfL2p;?D`vp&?>3)n-~&)(UF*-Nz( zHjOs#|HCHHWw8HIbLhQm+FS;_*6Dlo0@uPf${W#DL+6IqtjGU39-NHQ2MKae<{}4T z=GTz`p-@{kDk5>+=|;X`W&!dQxL4rJv@2>Q(3mtA7a}?*+3v*~q*Nkx%sFKuoeA9O zzu(#vA2f+5u09rImj5lxwuG^`e0=J|q7|Gk>!Q7;39rVvy^73{E!6*iu#6!$id2s< z3k{+qo5y*?=5-X0RG5>ZWv+_5haBA^M+q~ljSo*D#4H)a_OU(2M#E9lHkRu`r>0A_ z4beF?PB$@69AaiRX~7NXW!Wbhg^#dLJkREkQpyXKOgC#XZVNVHX3?r1eW{bDO9M|8!1)5sC@V7#P+e$X}l`-_fn~#<_e02sZRGi^R7xy zqR6zV1}Hsv!m?I%EZLNhbO3YCpArt=k3nzC%GTyJ19Pk1Py4Q&czHP6W;DUg3meJo z`m(f5yUj~Mn}P8BwVuIz3)rlWNbb3=B7UVw$gP408dpJj@(-b5l89C-}@=$VU;4XDG0@;Jj6;SF>NhdOKF0PPDE^g>7 z61lj0(n50wlrBST+BmX%O2m)6Cim2SxXDQTC)eTA!JVg4^pF7#JpX8QFH##LU>8^H=;RZ%)#!3PFbKU?G?GM;mPscS1omB7N9a@a($`NE zw;#NYd)3ChDckz;g7%82NIEBljQCz7PYV$n{{^KSaLK@Lx+Xh%Vl4>CrlT&3y~*_I zCTs;sFX#E-(w(yH#_bI?d-wV7P4_f949dl4m$A56KpG9Wdsf5B$%j2?TXS`#wvjWL z#DJHPR^eH+)26gCk2=(74f~gofTdAR!zXOdl>tCnf6O&_lox4Z z&4^5Jz`~N_+-6$$>@bz?h?^+QHd`v2ZeiEDjb29Cze(3|7;K*}T`{-WIMOXM*Avgy z8LBd)!9$IUJv#L6_PGZu8cx+Bb8Xh2@4s7C}t~_C2O-A zOi$u}O0mjf&inyPy{7E~b^pt=1vgUA6?6tyTPCSdY}4gw=a4g+OJ!^b&O+n-UNrOkK)N zZYG&Vo42-UXM6JH2u=sD!Ga^fAy+?>h#S5$)nE=_yhCC?@>Kw%SlKapOEcwd+6*E% zAj>o?XYq&i@M}q1Id_ekr9L*?flnB z0F6gLd&gJl)*Doc*Sbu-ZH+%|VUs1g4uX_HM2pGu(P8IhhU2<%$Lr0dt`*&l+tC$J zp01+?Q}~Owg!}4PH;<8XH2UJ)+lXcNva!r!#E~?=yF{Y2pCO3a;z*j`Un(B1{4j|~ zkcH>xStB8crXEC@@hCb*>y>QQO)Dxy#9hU0)3+lYl2KCK`^?;w zJv!6iK9C0X;&2{6u<4F3uuU!CnX|5v9d}l>(k(Fq_js&##gng|B5&b77xDXnQCv{? zR|;qqFCe$TF}Uceo_hC4z&5Ks4Un$_1XvzIytPSj2Nu&JNv_^sYQHtU1?BHA-PRq8 zBtCn8=}>PX-$t_Df2h=i2QU#$eUV2A|0eC520>mvA^KRyIPtP!c?klHCFG8795%hm z@b{ro>z?Fw%&z6l|46C0v+`;hZx9^S(u{i*0`n=va^ucl{AQ~FPqx#s=I4jMii*YM7(G% z^#kOy7Zw%IY}qtYLux#5o@pcyKR05&VoM}CKX_>PuA#%M*rl6Vc?T$du}jt;QpHK` z6qoHpH^C%QLg->gJ1e_=cV*_hy!tIa{Gs|4LKCN>l`-9fh!6*)mZ;GeE8 za4B_zI&*vlF(%S^STj+k2vxtHe{JU%_<`zuNU`g%ESL``|Ey2_`ua`UYy3i`9CYdj z`f`GE5U-^P!5Nr%YWr{O=ZVImmjZZ(5G44VXpsB*83&+&d-Cy%mRE93U-{?P=3js9 zIyB_pZT?$0N&nJ`sJS=WTc59sO(F@EGzh(Z$@l%bp^zq zonb>G*I2+BE?Nt^uP67w($}PAovg^Fs{2|ObGKqy?4YK`%$-NGMQ&T62B)30q4Z5DcqLz?Yrcr zo}n8Tl^99vgTXW|f9ro8N5P3LKr8kbL=yE2lVjU(ZtfIl8peqDNNLmNJFjEbW`1Y3 zWH}8ed{6RKzoHM=4~2;J0#D$3o;oRtJ-%0FEQcGUF5~l?ouL|b))b*)!rD5gqI;vW z+>30fjSEbIk>Cr9p<&u)aYU9xX#vFmGRJJvE;}>PqWkxAu8h+xJ=om&H7>s6a|W-! z)Wvucj^Q?sBWvurT#SRB)H>NYqMqRWrOynh{F7Ag@SG7G$Py1&a48@OyO>0)7;rxwQoE-uP!=Qx2n2|B}> z)CEsPe`{|gm(;T&lR!b)W=mQ}5!SM3hkTKuq7|iP(7rKwqBc>T7&|`sWM6%#%J1>| z*b`)J8m#tnA^VA;>cH6eQ}x>LiOK4Tu@O>KPgMIx2YEU=S+Dhv_|vwKJr!%O&qA!Mh8Yt4c1174^(NPiiDq3M`|Z) zlYBQhcEGybSg$&Eyn1q|K5&9&`ub}lwaKTf!{fEdQFTT(rUcPpysti48#p!6SFetr zs*jIN3{^F;YNMG&b&>-ixQTnV7JwZCi>cok@k&(uMCe^VgM~CWyK0nNA{}50r zWw*Mb>!)b6J~S|?0cF1iEag?-2#2AG@u7hlzrY81yn*Pc1EJ9gl7%aaci%{Lu6-)!Rlg``!&`6N0ODlooo>Y1r) z0206fw_E7FB5-pndl_msd+o|f9yTAl!1p=IeHF%;2m0_;fF8eubYdHa@aS#R?OrfI zCUX7JlY`9l+wp;+*P!=DDZaq0Agej-gF_Po_1ZXm0)HH`%zle+rI~0#0S+>%FE3Yl&2K&!oq0CjC$Q@Es~)W`%*|(WZ=g7^ zv8i-;>${5|gr>YFhIesldF8^?Jd_1S_dRm;e&EF{T3d2)wS=W<8CHxfAdaT%)-_gH zN>hZvK+>46hdk}X!Hdz6f;mulov zRpFyZu&ijSZ9n6rV`Dc<|^wVTXB{(L}l%#R^3jEYLtSbzF+lPs*OSg~9^~ZA} zXH^6<{4?df5KGLv88~K;;indekInd+pLEYWCP?v8GAn|lKI7|ZG>#i*DUZg8(z>Qs z(SG4f#iYu_8WwHnvpUX+gE74|u9u+XnI*`1H5auWR#SK@+{c&sU~heuw$y1LcS<)X z?z@go8iDF|FgjC*`c4C2lzE|nS9`aw$=(WpbuWDY;zc#zlGdZw5rv>@ae;P@G-{Mr z*HrZ!hla(AKK1KnPihV}zjafZDskg1YR;spa@_x+B(#9qf@-Vz9L!TXv(+d&4=1pId`XavInP_Y(HyJh(%_KRu4)v}COC-2f z3Jpsb_w}vq$-hgYo$p(@#j5fPlBQYmJ)DFs&8;sp!{z#ny>nsx7%guQDJ;+PW^#&r zl5}$62n6Qs+!vOHG=^j!Q=Vx#HgxuMDqXfh-8o0v$~OKH4J)BbpylL`7VScIh_r>T zBhp5;WNaf;HOTiuO0wXX_N?b}b3_VxgTSh1N=4CvbeW3_9NJ0HZ-S5I<2{fjQtRyQ zlnRQ|Yjq0a%aU?+Ya^>Ejlbgf?QA_Wby228&tMN9lH;NB^QIB};k0bdEUZn@rD<4Y zDD}M0QZFK#1*L|arB5tF3Y z)g`9WOnVgi;#QXeWoo?@CDxLFd)f1DGk`kOlVFmA>UMnPT!`LUCvMIPru8q;#25=%$0F z4uQ^ExA+cb>mvQcY1e%Kv@;cf(eGy#ah5|$QC;cS*OrVVNm7lT9tT<1EQxN|^3J;8 z9ilhP=wO?hv|DNbFkD4u6QW7OS#a+u_VSRzF~5WRq)jcbF{$oZQd5|QKeT`ph?g;{ zieq4%sfyA*k^r)QApLV|%en>{Qb7cso0nI-IH{;~aTb*qr<=esB*T!@5k|nMBzi#B zp%LiR@@?kG=`4PP3kzZ;Qh~7M8OpkSON(v72%GZ<9U5IC3^WpXbuTk5a6EOp)B3*Z zMQH}H*^n|rotr|a@n-Z)=MwY8%Jd)2`IyDwtgh9y+d(L{?TByD>VB&(1bouCFe=~g zC~yHqjVNMIN@BWoracouM2rn=HSn@2)7qs*1jj>!Le~<~vR~lo7yW%lq1A79qX-n= z!QFzXZuuw6X$o%ZjTz}NtXxjJyfxV}r1bgy&u^|SPVDWtARjNhF)C88rZBcHm(KoG zp>VBQCY%BK_rSU6D<5!f%uPBXEd&kSFG#<*7#zR+D8sDEO zjqiT}N@Ld~?`^u%s^3{I>F3{YXB_FtONW~}D*suYnxutyxfsY2AbFE@;MoIc!oLn=Xi zTSs!UA0>N$vj@NP)wPv%Id^$cxx5L#b2e$2uxeZt+blz^8SJ;z?RR-kvNfEdLi*cS zEO#ecg9GZGlBMFkDauZGp@AcXdN+pnq=OGc8tjiZw^$SKo2J6 zUT^n7za_0Ryy}!XUzGm;vG*?EbzRqeC(gN-Ab3bo)Rjb0mwH@XJqS_+Ktc~ol;j$G zNsuU#20`m(8E=q?K!5>2k(5TGOzl{9oY+od=Zj;fb{r?otBvfh>F30bC(YDu>bza2 zahvV^yCDKE0P-`Zsb3>A2xswNaL{JN*7hX8M<{NH~j0YBsv zJd%2*$0m#_oSIyzhC#y24F!x~>HvwIW)@F!W=nkpGhA5l+mg4W;@RBXtOYPvzZ~PG z89JT!hQ)1}Yuit*VK;?W-gl-LBT3e`&jVHE#>J-O_beLMgNcY;j zR%XC%|SR&Xutw- z04!sloXpHv6$OP_Ky;~5{krfWq>Muym)r6e^(b@b*ML(yr!OF9)NcqqT0?1iCWDWq zi!1f5?Z2BK6n=~YLhUU=PCXc~3Qs_HLpV(pWB;`IYgA@C5~nN~N2>MUlxTm~c4b{i zg=E298Z#khegDd$Ox{YpOro4d@JYJ6hV1X!j%ve! zT~R*Wvc{UPI3ge9?e=zMovz_+ZqKfKaB3-^(~xIkSZQj_7qhDm;ZT;hU2JbGVAl;f z9yU|8ZbsPz19rkwZELpfG%DGVMchIRL2HJ(^x_!Lwd=FYeq5R-!o?7>ZpfMs>jeO8 zZU?~S^4bGgR!|}%s+z;~5osk-?9G86Dt%D9ExUXUlLI;RfXoL^Z7!GT^-quU9*r z5Nj`H8_J|!+qTj`bS{bvX2s#X2=!3+k1Kb;o{L?V%WD#_B%1(SDHxQ*coL6m@B_KJ$_%Qh1nf`Jgq(G ze(HxfsE7QZ{%m~t#?s4&fB%q|Yx#@hf|uM~uU>Mw5u5dIcI>RV1D@bcq38>V^zv6m z7E&rPcWf>>Ubm6cGc=(?)o zW_yctd38s({fS7rx#L#*6A}8F&=%2jOUI6Id#xAOWc}$^+N~X4I1?9G{pl~S>v&Q< zb>RZ5KmFzP#obwd`pX+Sc3DgA&id0|-Wd7>X#MFg8y#LmW_zvTek=xv^yxOWgL3D29tU^)egZNdD=3!<+US0A7(&ajY?&?g6YknemfyKNDjEYE5^E5w5cC1s1!y1T|Q^y7UrMx8KD+p9V}?GRQ6_j+SJ8#t<|8snW_)^o0Z;v=RMiys#)5J#^J7x=ac%Ut0d%; zWuDNCl>v9n7TZEM<)BJsR1ek*uYE3xSD?BgHhRTHdxs54N7|h*Uy5ohamVNO%^{>X zM!!o-Q%r+^f~RtBoL>i5#KzP5Myuf$71tFM&o)F<+sR)L`Iq~yff93csWrX`gzrS9 z@)$WICr+XwnLo40G`LCS6jbumCwBn4Ajva z&5J785U_&>&wQaEP~!hkXk3?E;y1}_gi6UVZeBwRT)Za&5q65$?&_+E*g8dQcc*)G zh2`(}v9!B?sh!g8!0a z)ls>`xO<<9FD;fa5115mXS@Z4wCa=4)+kwIS18~jskkeg`-Kp@6$qg*Ds>7GnWg*t zD2_SvP}>Uq?`(xa>w`0)JNg)`Iem>b3lT63@j_{gCdx(IKZMGLO|2y^LL}jY2jNmm zibsSHevI0{xo430qG=|_$Y19(b9ExyUccl!!Qz$jydO%BgEmf1WN~`hTn3-JTA{N) z15Z^ST7&|xETdk+nni*UsqR1Pn!oa>KwBErl`bMYD0FYmat`g@6OfaDoJXriB65F04LYeKMjv4Jfx)p)XMWRF3l0QLY!C zUt=i8OY3AhSE+w`O#{7^@>rEmJF$B1g%GH@yUQe(+D=^ zL|UM;UiGtW2&-7#cNrbfIgmxH`>UJJ&weCE{2kr;Ss{%#6rUAV$YC@Y}$}m62 z!eO>hmU8cJGin4yzrB}nbT?C&n8({wVvn6^aJy02LVEWN5chZJke}C1^%Zu|$$SUt zUUM?vK^1n;$$SS@*g-SZ*|>u$VF%f(&=))CRK9~MzJv54h%Iz*K7G!_7O6w zGvPu^S$WskMN@vytT`elBm&lDxsta!={;j=AQP84&UVsD4hTW?B=V&=IEsBzESi|# z*sN;45wOEJem38nmv>#zV{$O$(C`h{Yd+956_OBXVUDyzU*6Jv zvK5B!e8~6~GIX`5#^wB4d3TEiTufBE`1W@1VL{j;?`dRR=#4k^1m1)fHOePAjU3A( z7HnRQEM{+qb4XvJ2^Z*yQ|c~ErzMn<5$x2|m@OFsjx-6}J0iw)=(ytwP;pG_KZh^zS!}DM1#J`&&((#F}QheD^vMu zeBI#yI88Z766{85v`|srOsBeeVAY!itZ4ImvFnQLE3pE0_04iV{trp%eCXk3gtZht zX4>CiTeNk71U(|e?w8?=w%lz|9QE7HJh>HcP1mh5%I-5ub}-99!zH6uqEy6yY9ks! zLOm|b7Y5BSO|KN4f@Gv^W-Mzo-%^Wx&pUkNbTmI59v&prPgGT_^j^yd0MO;P=r6H-s0rU{)GW}D&|UYy5&UEJPaXyM;Zs@Mc%_@Bl4 z8m;MW*q4T>tl*HfRni`GpZ6cG1dR#X$+j=0ih}b;$)6iibaqv@3fJ}fN$dkCbocao zlv7Gv3^WZx+QPtY}JPqtl3#2FT0-LsMnnJ_$V(NsUAG^Hq( zK5SV8wb%8>j?mzh;99;>I~hmC)<@~YcDUTV;Kngbf$id?lR`QG+!-I4-8+-D>*FJ{ zduOuo^6YnPc3dVpzb8pQlvL`!>N_f@%&~8S8nKU+yYLBjS&F{|r-|ccif8)oO{$Ih zgT_7#tzn|kW2!&^t2RM+hklqQ7(^FFhAK<2InpbT6#Yh$LR{c+b4;FyguvqsH)d}^ zF~RQUg#Tbty|w=5?uX<0EP>&yoAKJ{q5vewW2M76Fs}U47IzHXUp8r-P2r=GHo$K~ zfdKP?MNsih(Q0x+R}iT`a>}?(jmTjL+}`;bA$PQIbf576{y2Ub7$TwP;}lFXoC3xs z8A7T6(_+Qhpuq@D95vy~7>wkeOQVmUJ2w<}h3Hi-6M9L#W}q`%1}sIO#jL}4!7bFd z#A;2gpV471A;;#36FWJ-)V)0*54H#u!Bq3v$+BvDv*m*vz?^2P&7zC3Pe z#7Ai6gUQXeWOJOjWZ3*j((%tYaz~AB7u*QVY!(-##+RbEkfYnK57D(p{BxPMx2-L} zttakMEb${r*VgO~=+!cC{)i6UTWxStm@K1Frthohe8^L6@>R?frG5A#@d)!&n?Ir> zY=P;eway<;I{p>Yo4lmywVIJHd|_DZZEGE-D8RW9nOYF(QPMc#LXzG)x97B~FqWZjjaZ*jw)PBveYEwc2L zTIbIs9sfH^PZ4()34N!pM%rzwc@g4nYYl`VZvpf(N!Jb88<<^1YyXKPy`}z8$v-PU z1;jseg;FV9QwNnL^_7*yj$-SV1HS^qCz7jgjE`XD6G`*ttlwbb z$4@2c_4Qj?F|PR_DW6-SMl>s0Mtj9_v+v8ol_Wd1Q!x6Sp3ZO#0tw>uJ(!YMsBBbo|mKPrA)3<6@I;ZyqMS28e!9lOABw zYc%Q4YSMRH`lN$WB}|zvm@<9%lzC);&&Db9$do^;DW7J_owd$iO*;MqQy#yhb#C#$ zxY&eS8;9w30?n@`UDsu=WxAc3?yqaQyDo9MXVG{dvV^(vJ#(c4pDT~_{_AnBJTli` z*IfTV(rl-g*l#B3w)%f^S@zV}xtUY=y+&U_5s?iLuicoqxsss>v76rP)HE@)*v6l6 zsY6XOE=vgTkY3QEm^h&udMW2!@DH^RfZ6lvGU_KJ_FEjR3&hf6=w_v8_er!U*!r+g+0KVi0Y+Xy_`}GAP^LLXD zyguq*SL97(uK9&sFiZG}KS+jgg^G0ft6k<3;7qx3&b!UoXFEB6@_ZFhNHfnivQDfFm&@UKR{VII zywFFFhHG|AU}2Fv#O>&~SNrQSkzLE^hRcNea zY>fF|^6bJaJQr5auG5oe*O3(O0;sscn64f-oYcw@bx6*D&>(4^7Z7}diKM`K%N&7H_?M#sEV~*c{$h6y^WvKFwS{pGg8uU3Eh%Wikz?Yc!_{x@a+`Fif1m=#`1 zIyn03zji(Mjr{0E&McV-PtW5&V{A?LDSU3GPRoCYcd*4VEI~SX8&*FKiPr-1uuLiS zKH6qnpyy=G$1P3f#))~%?&&#KBsd0RGABL>SIkRPv&E>5Mzc_$6KQ(68L5Y(CTuQmTx&(~6`|e%& z#C0d=Z5)~!JDtCh|8R2=6BUZ;rkpQLrzJNgTFFIAXAthRmhK9}F>W&8Ro4u2aAL{a z6MQGKyF_tZF8c56AsM`?;LXu3eW>>$sx=S)Y)MG3_3X2jCg7XG4_9=%1KV9<*REZ= zd+dM1yLRod|2--E-^)KeyZd|Y*gf2T$DX_H<$t|;Xa79e+t`cAl7%E&AM35VY?vZG zKPNbEDdmxS{IPdlf0aFg>CF zt3~h9xuxwgvY-;QJb}un)wnrci5Gc@DHeC{A-Vr4s$ikzjFPQ6ayLiB+J4CD@qj8S+Z#CvIbnrDp?VEzNIRdUj{S0Md}((3GC-U3yj%ywHr6tPvN=33BW0 zhI(3NNXp<CO3OydMQj33)hO@ z+%~-wAw5ps^1JT@Lle&|qJ8M@?)Ep^r*bmWYr0tFS?{D1EzrFFlFaW_7u}C*>ThE_EMgswEzVr%7z!Tx$2-%eRrQ0=?<;-FM%4=bf*)<8HbM zB!r5K{XW$=J~wkN@H#QG_RWZD;Tu^@QmccJ?V!Su(r1gsdhOayRh<$z7olMFBXq@n zZY}j=1R(k^NSy4;s}O)vTsKC2A$vpCKP||kX#2=lUF<}0Q#h^OvXrZT5SL4x*nYJQ z;(t9*?C0LOsk3{}%*>K3qVTs?OS1qBZ7x(E&iQKjG+*-KTE(zL@{ZY*b+c1xQJ&eX}Hg+x}JGJW^LG!E!s zbu@HuFU?$?6tfSFg$i1&IMcgVooQHLTN0hlt+~RN@+B)RRLl{c|0ti#eV!gtYs~NB z^_FSpQTGJm#o(O3VJl%Vaz$>5BHS|ED!BO35o88DMmd09(fQ*;Np|66n{k7AtXZ$U z-h5ti!wWsn{;rUbUqx;tct~Wr1l)0h4%7;q^sQ2NKtWk#;t0DEusaFrGD+XXrKD4)NV>y`A=kGO z1L1Y40xCJTOq%rMzV2}@=XuJOJlWi?1(4qm+diu2+ek@L%UH`$#4Rvd97g#-O{S9s zYe{{*8nh%>eH+q@hMAFt%90Eha7gSW?I|3{#I=LSgSodvvwzp_*XVTEeb?}=-FxoX zwP*KTy}NdUJ{QY5Wb_=Di--#Opju0tGj1ul+A&;ISjeOg`)0UI=x$fZBU%{yEtDm`Qh2 zb3Mn8^`T)|?0al#ysrSIZ)nOg-AqjNJvci*J~lgY#L{am_6eZA(jag!w8JOoAp^L9 za~kQ!#bxCrgI5$^h;Vx2A2@b-t}e`*X61CjG(@bKvZy>on8YYtV_JQTmSzOhy{Ekj zf+W>`vN~C9j6NIeHahnJI+?+BHWADpm=4cE9k4=O@SP%)_$q)F}8Dl7<-q5`r(<#P!I5 z^K`dYu?jhRSq*S&|9<|LH7wjMPmtx` z%D6T`4lG@IxE_WoAGX!_(oSwOe3bAHg}O;cwuG1DEO17q@y?_%RNQa_ zt5WaUa+-~5ml7UWNLiWP8JCG!d2ZbcU5m1n?nO_+xX8G)$judS-6v3%5a5fMbp`!9 zk}mfn0eF=5?~or!@Ui9B@0QILAKSz8b3JoJv)Vm4a$&noL(qO}O?fez^CZ@hA8pu^Q{J14RtRF)u*6_=vB=`CI zWaNo(7bcass{#P4W#wspF3r{-0HMJ^T&rhm;s1&W^@JrPwuvu_yg8|5Y`9?FoCmV5 zMa2Y?@7q$%Z0yeyJhU%X@3GKuDF38Jf*Y^3YdLz>4TY!LP1y!JNJql2O3AZsXuZ9A z2qXX0LTy`?1(!YCytk}XgS}n<=Xd_vZ*`HiZD?KiZE&*onrxHzRcfwW6s6`5B|{sn zO+e4!nupa{82@uNXE; zQ|w-0ik?TPZCcI6>>5FQK#9Zlv(2bh9_C!znbo`q^oS?*8j(vyNN2OjfAKGdc@L3X zVRhYG8mHt8S~qmL{ZO=Rez1~lSw3pO*+h0(%dj@$`u^9(d>_lmXtkbtk8#e-PWiY) z8_E#ZX0uJP3Vi_BEu8E72VVI&j}odmgGafKv>4`Fyr>Un8_KZM_Qyn2No*yWs}4*ZH~vGSav&4*d( zIEl8gTKiIRsf+aWeMxrNfpe!3@gj+?zQ4L7CRXKHG1J$+Y!kv7MK?y|i!>qu!Z_FZ z{tM)P+UTD=#upNSn)6vr39Tku!Mna~`|quMc_1x#z~3ip*ZFKqX~08B0TbsVRxUE^ zjoEsfwnkuO&}}sAXS^EnHy2A7#u7hSZ_*lN@*;bb8-W(|*3}8n&L00#%-R21 zyyT=|ec3fDz#!L6xhxRmWUdV2KK{`B$uzsM^o3(gN`)z?Da>Fl+b}kJ`s5h$1`bt| zVG<9oI*E()*E>+^>;RQM&kwcqf2otLe`|KdvaV{IvI@1E13%WEwS(olz3cmTT?*WB z?!sKC^t&g$Cu#m=lC2kYN1A#~)`bzpcZYBMdh9+5AHCWMCellIptYWBJy~UGX*Q(X zTYX3IiP~L?tdYc>JAl`Uht7r#yE?h~RD78^+~aq9*JKp{EuZX7qVdYDS3kp>2fSr; zORL@WN^q28sQJrC4SO-XJri;Lx@=?I5FAdkW4_22V^m7r)KR-ETUR_L zq$24&K18+9;Z136L)Jy5K9NJXr|JY?&RWd;BJ(cjsEvwEz?E;$Xt5b`&@@Y0d zm3lh7X07EWvS*5}$i4O*%9Z#1X^rHME}K$WJN|X~^Wi#xM568r|K<}LWJ{~?UF&*&eC#=!&&_SWT>1RBo;lYJ;|G&$lQ3GAF>9+cr}n0C zxh^2gv~?bNTJttrxkhtq+sa8G>6vtCmnE!yN0N2=$z5BW_*;(lOC_E@gW%fcRc#QM z6l0nDE(;fgol}BpS5kW}Tf5IQp47gnblfmd>P=;JEH2c0LUt8k=}u}CAKJ(D|C>5+ zcfzFJ$#GITEo-;0xz#5w8mk--eU8-p?PiVJWm(mnU?%RNp?kPC>IB6tJB!B zw%-_VI}A8a>R4KY5^xTQK>S$JBIA@LmRE+qdoBfkK92ndB2T+O*`v7%K!}a*@5fY&T2ck^Yi%GY>k~nwbeO&`P{9qzV}-W zwB`*4)t2U!tyme?84g(W=4S^snj_6gazgBR&7F7O`yHSE?ay7l{@L9l{k!__+;!)! zd-i^7wsoS&VcCAtQX1>da!z*3Jc)W~vF`-`p6H3~`!GbHZ0UI8|d|~m` z>I>KqtZIgN7|Gu?&sOlwNK6^hQEn>IQC<;JOp?)}=5^4CK_p3~=b$7V%T?~zM%*Gv zDlPXT0o^32^wgDWm88;BSKP@M4Yu`Q7B{y5904Jh zrYyQ~(B8B^dszA9D*yUtf8xIZ5ijcZg8L~e7bA{U;`n1Trx8$}jYVjA?A7CGDr@)c zzT*zEfIc46FYZnstJEL%3HZ`r|02P~c}I@w`_ z5yG8QU?6o=By|f%XYjgkU)P5&s!l(}gnx)p=UGTW2 zJaAw>Sm`t*eh$_tTp^SUm0=&w6v2_9l_YH@A6Shh8!W279mah5vD8&YI^%+i{f=DI z8=P%g3+I@tEx7Z+o>s=&O7Y6zce2yU zt_WtPeDbn-n6ip`oV@k+_yht@?z|@;K&eJb*~nr(zfv|bT2$t%_hl%sm0&U?^y5wa ztzhKH{v+L-$&=X3=C|(&#dw(#hyo47@{Rhs?rA*L3>bnkoK%`m~+Vlpvl0-!SO;S;_#j>c8(Rg_Zh@@}m7#>q^-Q zgqxxv+ZV@I4Iq`q=`nfIXf1sqba0Y-oujj@wu>mZpaJXIce#CR*=Z-(*PKw6zR>BH zKH04tgCYa=d>FHZnsRRDStKvG)?_EBoawwQtfyp>GaIjpPptfzs~ho&wLWwEYrO%&s7W#!+O z+z?lOEi3=NJrJhb#dLotA#+kB^sX@7@Y0c@R{ty^pOKjVS~gQxm0alY z)yEwr>uQ}ZC+Savl7F@WN=!r4=oV(SUlcXarQ(GO+!#IQcPjabN_Kr^7_)mIdrzrL zIZ~%2?>kP`fw7m9PRn7(a*hY_F?B(R)e3z{N+C>c7k}wk}{SynKC@ zt|2^)tV5q7JdGNJTwmQO2w|6GA$FtI$$-7k-?+A%~XZ(@EEr*+w~U zDhJ|clJu98idI0+{QQ}uYg6``=-c^=q-m>fH^jtwK_QG1?)ZKT1kH+*ZAjwDmxggY z((NxM>y0M#$nyMRa`ooyE*pg(e@Tf6x7jELZ4j|_kvNNAuonpQ%R)YelECm?Ogt#! z`K2Q9pwcn?k`fQzV`H%7zos-^J8X=c>@Q&|+%fcNoQmk~*OK*~(F?j`m|s&yuW=iO zr_ae5cDQkb=trrH!a?H~%i!d!#f;m`2ml^wVpd)+Fp85Rw?JI^yb+5vh^L`&;{IIB zjK-sZfJdtXgkY>hIsc#lA)#uJ2#``;{bsT*t_xBrk6W(Iuwt?HNTpv$(k~`e<)NG> zyX1t}3pWenI^pP5rCw9L*sZuX>RG}K!hO5pNPTzq-*H!5m^DB_&k+iVmS2dO*BBNk zzMysD)DRRL5no8Qd=bLGGFxvie)*68`a48J|1qiV2(Thbekn1n(|B})fIq02${-tEw@8qC&c16(tvq0YiPa|m}IgkD;JZ)!S zX>Ntfc~6<070k;xgm6I0o~vwglC7{-{R#zTD>m;95Y-~x;{*TwQJ*+rCmi)IO?eO^pbhb9ZxSw&K=J#>**!`Tuk190>r;g((cuP z%9WFUKcJ*rW1tA5yy^csZeP+#8W<`jY1t-4hJT&hwhcA2<$U~`q~q;rQon!Yjrj^z zL<|2nNms*;@(N|hI{z+7|F_hSa-RA5@2JVg&z)5swUfUst=<9~S?ka29$s8qyx@y( zOY1ilF97}9QW7&tSg0^w=bO{?+w&1L(Kn~rwP6I~6>mwa+rsxeGXgKJD_-!$Thi;B z#S2DwOA2p8Z1Z%KFQw^ChB?wi@;Q$i<0BuxlwN*aeB{%Y(i^1^(x?3Rwlv)qeiUcm z(K)K;gM3>WI4X~P`Zgcc@lhu1q&a-*tOk|@@y-HaS+hl77LEbBWoyu{^C})0^n25A z4DiTgzBlCRq&9993fwZ>|@j9)dq4`kS@nfu>i`Vhq5m)Uf>W<*K+`4p98hj}2 zs%N(Xx8>CPaGJihevP3G&?H2$NUn1WOW`TuXy;4eDd9dGm%>xReOOB&GUKs}t9W|# z1KFmm%N{?#Re?8~@6R5vK>^{1Q!?)M*`Qn=$61#`cNEV8SMC_!Syz2&)p?w0vY$y)7c6*UE89mIJvh#>g4FekrsmbMH?fHJ^>i!(fe zqhCq4-CD{j}%2+ST`1OlX2CY~inmJ|gXkP`&;E^tWU6ipC%Gglr{CwK+ z6)3|q#g~uV$D|lpP=agJPbpcRzaMNkVDp=;U1eb-{8%G|I&z7~3 zpG9Np)afOq01gU__A&A~O7H?Mm(76^sK1&uwIS5x#bw*&HJBCoGWK);^v4TtWN5qe+>^cNtbFKZ`*DCO$h1E81JI{z%~__j(C&ZP3*HAmpq&3idr{h6SA z2q-TXlz)+?y>$r-n73N3U0Qc}3A6glIx5g5aE;}Z7jR2YfJ|2|;q%Bif01q_yathg zM?n6IbZ3ukrpv`M{whuXE^H>AY5iCEX1ZKd`v3fYZZiQEa|ABmOgtKxVKec_9RD9} zCS4sb7en~lw0c9hIkJ#~jbv(Ddt9ct!z+zfFnaaXf27 z|E=zBy^zKx6cd#W9H{FO#kGEcTZo2Npp8xR_2vq9-w`ITNwo3S3R~;-ty@dVdR>I& zPl|&jyfsuj3&sv-<%pt~sg=A@I(sVzbp|7|3h{)gFaX<;5qvxH$nbBigj+C=Oy#YW zE3eAaExcZUdAH&YFThzmGUiwDcau(2n&)jS)~=C86OpSsx0OsX2h_dzI8+E^yc8q)a+#Kb=g{2($f6G zd5b69*q?js17q*<(R&~A)GVC2!`hlU69U()71 z*%}+Hc6D~evEe89sE3VLF~;iFZRr4HMW4&BqE+TB=4!^K^>7=dTsgKP_?+_gG#orzCUkO z#$yi6&=s-c{MDYh?8^8Ouf=H-R_Etx*TwLb(r~j=akL-kV%667-w+#>M=R)bD4)mv zyyHD@w0sXXyV{NM`+Sf`-MU&DN3*)vILaVlJ?@>$HkKkl0Bi4ML*cihA$j^h*ny?w z=`qqHcn0&?qLTOYjpY`-#rsNs|5cKFIIYT<{_yt`E?Zl(vE%U|4i1_s#`m5OtPo4 zbS*I5kltHAO07$dRE|#fCNk1ncQyU=C3k&`@dFU4+ftUeX@V$Ob^e(Gt?S={;8 zs@VM2wKx0UI7Z%(-r#=&;0-t8o3A#wNZxSgJ-{uvZtA!-$zA|1THKQEuPC!`Rkp3Y)gVAPW2_tfZy?*z za3~SWDm!lP%f2id2*EpV?D!1E$Ioq$tC2;&AS*=)MYkW5uYIX?l(CW|5pzylfDlQg zl{BIavpba4#7V>pk*ZrflEthMiQ>oRwY*?Hn8B(mUA{tzq&A&7L2Y5#GxAcgXi?=X z$buSpWOG}j3fd`BzUh`4Uz-WjztrofX)JDKJ~zoqnp?<;yoW#aPn^Q=Jkf(ir5+O1 z4$5cIG?aFwj}49NTG8N8;V$I=@a_Jo3GA-4S_UYJBzuWiOe#9zpInrNgctgrr;NLeQ*_ho`a4e*7IjhFY9IAoM7@wMKtV<-L%vuY8W0V zN_6_n_#*D|e!%J!rJDJvKEqEaFQjP(G^>4#yMI3X^#b__K_<0@?Y}SNU%e1=7*m+Y z?g&H6$?S=-Q#i32HMnd)J3s#n`om|Y;(|rs7xy^6dtM3LuLx={A1o~r_|AtVMu4R3 zr?~1Xu~Ec>RwR}$<_bG8h7nooe4Yyx?q9P?4xRx-^F51R+=+n+OT@?5;l;?9zge+^e^AQX#%wQygg`XL**f8;HCl!xD)L6ik9aOVpXXZGNbYe-9a?%bV z%zl$zP=`r|)+C*j$;Pt`%j$)1at;cb9mc-Ccm}j7To`_v)Efpn&)!PPN7(X7uooYZqs3McIcBCl_G#+aU89B z;r1gIlOOSDOT=fG#Ax|J$EUP>bJzm$swG-dVOQ!_Q|AB6cx5lvySNbOl$hO?;#spr zWBa6$6IzD0J0+mQ4`z5b)o=?T3+{Pf5rVtILRdiD#&B9t0>a zN7yFm7BKpdUd>DU5t?yu;0wU5!Lvr+Qv*Fuj`ckE^i%wcKX>)q`}FO7WRG5ows(y9 zlqs>axu|2$5RRnG#c+!}*ht)v*}AD-lF!kxMR@!^HR?XD5B4E_+w=Bb!&|J4nmZp5 z$`?bIxP2;En2jObvEW`2%j_WPP(TjSMsp0H;AOd8!OJ78n-UTD-)CBKV`EwYadP7bX}dXZwqb^Aj_0P(tsxbhd61c%m*)Ho^Uek8%G& zV|FfDn5KzPZ|l`DHn)xV#XJiIJqN|L^~1m?^U;ljO6$3J9@Y4{n2UaF7Oj5BZ>$Qi zxI7H+5MzgP(KfTZhf_nVwcfZUQ_k`h0fJ`cPtB<0V({Ssaop+8oD$y5yxUZJ9c{jK z?cp6Ck}vl!R}E}t@lh3;|G8=#+?Om|=6H-73rO1UU|iydMIR;yEah7!Y5_`;p~YB| zg-+QIm|?_;lRMpLu3=Y}1@kCQS<*Uu9l?pURhVZ^5^%gF1*GmlrDl! zdvYLvoYnf`F2#&j|{y7&Z++gPW*<_m_Nkkg(Uv&6$ z1fC+%fF1Xu2b6tW7}yr%dx_KEmY;X6-?Q=aHhsC0Wt&|=#9fNMRap*BqYp?haAq?0 zb82i3Sz@7m<>SCAgR?ENxX7<8w%)?B11lQ!*~Zubruxi1i;aCl9=+jZ6cjM@Os=o$ zotgJy7E5D`&tQz92FT)KPw{(?%rg@RVe_ZRcH>IE#r78@dx`d}#Xk0Flqi|EnJa~~ zQ*vdIGXiOXCL6k-7%C-x%}y=B$@1Qn(g#izgPRIxtGgpJQX~~?9GQ`v(LYgyc2yyW zPpDYIUpo(_@z0AHea$atfzfmSA?PsTElPp^V=>n_<^-1?s?D6-Mk9Jwp_8Mo;Tv`F zCL&6~Ud%lrO8)gfpR9{JN5Nh{ubuNR9Z_tvPbcYh^&d_eW|_6?T=!xO_O) zd666?y+{G;M^EWm*K!cg>!xEgz}Yh9=~9%|f%~8>wjaQ)_e5PK{oF6z)m64YI$8E; zeljUY46x&rJ8c&0-P_1>27EfX!eXa6Pdl0Nr;}^9W-}<>apC%GB8y`EDeiAjFlRt0 zmcz#78ejwErz#!;ZgvU2<9-I)JuH_CxD3tN8p*5A>E=#S(XYw>>+tKU-pFH%&LZa=!w zh?8MjleYt#&BCs={y|HyjFhCi3-~9mS?TW24aj&-q<>U6Lii{d&JffidsMed;4!tR zi;-#DwYKuc%@JnztmQ&mM7~mXA9Ce6A*#_sznxxvSO|9aDmy+ul*jeaF8+FydOdRT>qx!1N78pZkY}jk+%~&fD9Cb()75iSEw5#NQ?|}LOdh3; z(!c9E=_%+*|85VfSFF!Jg#RzilX&w|E7luB5mc|JV*L-^=N0S!3@?mVE7reSvHsPH z^-8|8fG$dvq~}jbmB5j;I6u8a=_$hFg408;1E*FW`m(bmOGE2hx)tb@8pgq{aqP&! z;l~Ds4m9}t=+Kcj4DLU$zp^pMw30&DLl|%l@8|8|;i193 z$MMZOM$W#0V|?1QUj`08(KztnJ&Go2KdIdamt@%G-!+aLY&?2kXx~G0Gq86M#nTfu;K9M+!y4@1 zks%K3#?gTxvfLlXg|Bh+_z-1`4>UBh{e#DF>!V`se(p1e8MATV4P?e|9D4{C!q$nt zTCx7siuJ7(>vu+9s+;pV^tTjs==G;NSlt>Ntnkm$pZ@Z;4$fNKyYRZwpZ;=NQSe@W z`pfRZ5lnx6Oi?j7ssC}(!O>U$p`DG<{Nx=)}=jtaPK(Z3Ec}F3H!DYc0%UwFt5m(2b2ER#QlF zd^D*1OvNfmF3Mjd0j2?;)3NKhMko0wz?=WdC%KE3x9%Oc8ss+rh9n4P4Sc3s;d4Afw<%7XFqs+Uin+$ZIu(a@@|V+WndFo``FXgz1@CbcQ||ErU#JV9OMf>RR6OILL9O4#<+) zsjzSQ1;^0c+c*ev@+zz7w{2OOMz{vara`>g89E59Eavt!ap{b2H}GW;quO+vMQ#MZ z=_xAY#u|GX{r&N2y!fHfnB=G3@s~#9oLa`m7vdl1)#wg?3NN4A)3`@Ro?l}W<6{v^ zGQCA?-$K zImbN)w?tCiZD&V1jNic2!?bke9S}e8+`hJyLcZn|4Q3&cqFHari%8L1vN0F2+VaWM z1;DJtcm>fT%K9;J3 zO&op|mT@(wN83S%^CZHNYls`zt>^Uy@qGHDJf8a;k;~(Vm_9a7Ur7o@CZ_% zbQHj|B%Wl_)W5}e1B=oQ2V>YL-TJ8<#km^*8i4>X{HM18vZb(+1DvY$YLuzzX&4)P zY2|74#reT93w16zaznvUJK?0N5#26hvB#Z-ABi{@qaAQMjF?}>=Gh3r%L4<=$r%*# zfo@%O3o(r?Fkj{!L9^rN#JqSuD<@3aupo0dFy0o>Y2#d&yo^ebK%2mEf^s;FCkLVc zNuG*R1SkxW!F5V5hx*tSR7uH~=F#SA4Q>DC&@p&O1FWSW1%dlu0jItWum%u(O>|aZ z(!+JcO?m}*?9%*vcixG^LUG6lyqtk7=SszN#9Pg8p!J9)K>+z#!*C)wEwuJ>?h_-B zr_Mp@!gl)zPD8#v`RbICkAt~o-^gD|{33W41ZrK*C8d#qOOCd)$+ly+nBr3 z;+V*mk)f>wejpJaeqMo%Q&W(i2*R0LfsGO*Ih$z51@zx?n1__qfD~E=J`;t-(#h0% z47Z-bD;>fUB;eltbUcLFcMxr{^mTVn<94;UpZGc+0!s5@;tE zR!T&P>CJXspkF`o7-qSQ6Z#4b!&C~kh`jueYzJ1Ay&azXwD)s2GAoJ+1dNPDNlLV= zlp(ke2L2cu8y~dU6}^?9rU?83#}xKYgrTBapODTdSuMuJyd%`>5gAg3Z z#||8Wf}`fl+*wM2SQ`6qMC-;9*djieA-KaWGG?6R=a8tFj>l%tj-8JOAJrtvlAaOA zS zLqnA1Uiku=D7LbwvjU^imJXI`kN}rIIj`f_uA+ip(i2m>`DUf{Q&k4PwYt61{JJE$ z(qfp#_AD4|Z$+XlB+nq$An!?kP$EvblG)x5d;RFZ@Ver!b>{Kr2wn{L;)jnNIovp)Y9d-$cE~}6FE<`V zn2^9WIA<4Ykx>a&NX>5A;0QW~!uS?%-(Yq;E4mK%8k7axY^PK*M^c;J{pI31#>G|x zu`T2v!Ms8~ES&44VBlT|D>hPIn(s5GW_chk^i0rvRv!smYsIu#mOz9e&2wYo^%O7) zt7Sy!7hZi-kdQ)xj570kaQyA)!aVzNs<`|fXYUA)3$jiH!%?Gg^dxqe#%cRECd1sI z)Z!~-pXS%=fTPJ7GRKXbH+R;SF2nDb!P)PNGT!FB+G@Z{wNuNhp_LsC5aa6#GqM;R zRz@x@QJOH;n}ZS6PMT708JOHW7F*ct!du;VbBfT`F!u`U*`(}nJ$14$&K^h42UcSg zVC8WSv!pxQhiSb|=%_t1Hx;#?vZ^ ztuv?6YTD?0>V9v^utoFy5o7e97M`Q(`cIRPVavUz|1_y@&5hCDwkNyIT|D}j^;s=P zUh$C=3m&<2KA5Dh39cZqU2mwdTE8xIASbZs5g^WLET4`lB_sXo^CU%UtZ#(KCqtH75m704QuCgyeN{8|{YH)XUl}CPzu(R_mySQZ?jk_MI3|;BJ z!Z3;-`EF0&*9LZG*X1zoI#+L~<8A%IV+{`11#&a65D=zBM28%9ci?_Hm*8;Kz9 zy(YVQWF>HvC1js1gnADCCAHmIRejr{my&qoKn23@wQsCx^WkjcgHuc8PDoT(P|n_4 z{@cI}7oL{L$G&L38MoErrj081_sW5)-IvpdXy52`B^o)X^H1D$D0A}A-_1v}D=4&% z&a4c?H$JJu*(N#jsI%zDQ`?%Y%X2{*veyiC>BX^`=cbe=$9}XLH8CxV-VD!^%CLDl zyQ0*en^tOfWNXf706J4blsx^)$}8t>+0K{Gq2V7{Hri!+eKd~P{~euK*I;0YwLeX= ztRS4)j^L5oyKJPQQJ}7(9`LfZLQeC2iIv{Hvbiy5#5O0Y?tXFLI{n!qckQ${#%I1b z@TLp>>@As&{}J~_=)j`1TKB5|Qrc6s^V!-!<+W|A&bW0STx_~tzx>+THTi6x*S2}U z=1g(+FAmtIsIe)sVpCiI;YFiMM0luI-G5yHfuXSlj6Jr^Yv;18*c2B4qG%L>*c|Z{ z&z#-^O2!xJw_m&CV)K74TbI*&ZF}r&842ZW;<&3*W~r%fpXO$xyiK(>%Bx?otl0Da zh}zD-((TE8eg?O)S8F@>^!M&U06so9tLxrER7B{aECb$zMRv`Oos~Xq?8L$pVm0?a zBwe``ah)Y@A^0DmNP#haoG$ zhmN2>DBOnROoZ3b{=wnFBZSc53?xsZM+Oh?-`NORMnd$WK$H-V;TiQKZv7^5$KiEL z6*##ziaL@f&cMbH^N`T3+8U;!5R`$8uL#CjD)YIreL;*;d zv)d{+R~sFNllpZS!b0koD4a*-9Fro5-|7H2$S-PtlRxI>mO8*Z{X^CPzA@J8y)Esn z)URmx*{5rlG1R=!F44ZXb#77?0LpGD(E7G3n(+ykZ|m8uyN!P1ZnLerBbK6!Wq0jW z_?nfuz4|aU5L9)vqxycbMB0m@gPql$8KqtizjGn7H&jdE4Ntq%yDL;n8M0zw&j#z+ zan4ycjf(c%;&NtT1}yuyNVt>^j>R>#{<}9`7k^_8ySG`IdX2yw`m1-wIV4_1%wL7R zn8RJw{xFBc=b#skPon$oO*N_`sQbAU#;A?^ zeaHEvzK%^9=sTv-cs-T4?P5<}tfBOH)vxMne}Ihc_Sh5d`IX0s?#R<@7U_)wR%5ro z>T%Ju?-JyCVjhnZ1Q4Ep{BdFcT!Fw(Po?`pYS;2rb;W*hU#EHOSA_i(^`^XEB26n# zkp&?jw>R5 z(>gA3Han5+o35zEC&qo#mG^~lQy=$DSMAB}H#|bKW9c}TUsHSKSNR62Jy-o`3u}ce zICH|Td#VTQLlHMv86#$b%wz!=+MC6SqM1u(`tcLy*k4#xP}T~_h}TB=p2 z(&_&CT?U4tKT#!J3>v?170{>%?Nknph;=H5M&vn_Lqm;)%5)A*)uEXN8m9q}JCj}; zXh5fBX$d3-oW~<1Y*D60Iar!Uln@YBnISmJQ9?XeW#)>j;uAp3T(gB#u~ohU+S#-j zl4tu(p?x4}5prY`hQ$YQ97=UnX1yA(`eK|}ug0q<#+hy0l&R<>k85j{h4jYyk9%}p zyt|agVvGyraUY1;uY;l-smAil&P+C9ZwMdyr(C(fg!MZ{+|r9j5AyaItQ=)!rQ{)H zc~GU05cv|4v^)AJGz#c(%4?bOLOx~X%3G*e0dCEaDKA`qL-wD1%B=6XbbI|*6U;1< z=G@Fxlvid!TU0Af{?Yc#{46gBrZ&r@a}o3mvqj>kQR13LK}A|0sVvpi3h2?sDt`qc z#>qPp1AqdyQ0q>Q&5~`!%RM++C^gFTB3imY%enQ&l|ck)(<|pT-4ZB{N~V=_+q%gw ztYEw~FLZnx&b33f$t3n_mql%Ogxs}8%P-^c`u@h^RxZC)4leCLac{A|7l^=XLUqJe zQ3E>NRKMB=GY*0b?F=N4G;P=eFQ%OaEKhv@;@b7`3D94p<|YXRIccb^+(A{m`jNjM z?BRZ00$fLpB$>A)U7IOc=Ox8D-K*l^G}!+GS~5bh~z`@W>(gMWYA7aEQ>+_Oii zvkdM3v35ck}}b^Mn}5Pd++>I3)of7zaWx!sGSQenf^TQ4)_((vK(bmT+)}U+M5;$tEu~;3eTcrfRWY z(Rxv%tycYbLUEw~kZ@)3+V4(kc(V1n+ywf6jb%4DMfFiErO!N+$h}Um#cZ%)=4Ar-y&l^}J#JsD852y0 zKa*tZ4yf|yAZZAcjGz0);{05&AciNspPa`yI2SA%;i>kIvMwmriiTh|lo8|RsOx3$ z-n`@9M?tKEVwGo;){oehQ8jv-9D6`g_3uEV-4`u82PmP~BVI5Jt6JNlI zXRyE_B~Qhuj(8KDx6 z%B_3fV8zJ{yyB}m^UQxxsRo=G6sZ%C6d!AiY<(&9WdN-Fs`+zCcI8n-a;2#j5+aa; zD*%}*?FHltAFTrGQ)O6JDK!z{Pi2W6S`Ge+{n`Tmk78BXJ2n}%aqVcf$!+BYt^$T{ zEn~R&!mA$SxE#9NKF^;Q>knlc&Agbu67^Z5fNX!b1XLf%)(0?+s4x$Pb8lp3GW4}B zycwLV-IQ(6*~gu11aI}RxOU;)eqJ@-4P|igHWS9QF>qJXLApg-L-b9G^_(VzZubFkN-uhF0W@|vQa zgZ}iFTZ+hH{YeH(#S2&aJ03~uA76vU-JRPdZQ;pkna7dD^uQ*-3}%Tc(KMZzkX~j| z7flmV(0mu1wN8vX8DJ^JkwEuwHko08ij9XsFEr$`n$j2HWM z_utXPv>5+s8uOl*vNkKuBDQUDgk&=G?(u^$5tT3;LMvCqhoPet3rOHABH22!F+!NK zVR4Mi4Vd@kHjISr8Y9$%$4=uPH$~iU9vy+4tnj82$PNw@U8w*D>qs`WiDyVcp88C~&@|ne+3CV0@v%B#H=|PTN>d(h4 zkQ}WZ{ah43p(I3DCu)^@$gcO#V-6xoz?xG|%TiV{RsN?^9~LXJ6vJG!G;ZERP_WHl z6)3nX>&m)(U-UK(*!FPhq(>Ajq(bJ}VLQf9j3YT-?n>dSj6@Q=1&-~LnA)h&Rx2HOdvdat~SSe$>+#^4sgc^Y?p# zFftfn_@DLq5rOs!3rO6(XrN~2=T6wPBWH1x*v`iI-VxQAM}VAy^w8boE8 zmieANON@t7O)HRv0#1r`2pVfcGHc` z#26T%M~gVm3u|j(3~1U|sS~sF<2Ic@5+RmqIgz#X>Jju0&d)1C0d}WNdy!G0=61%H zFRH9;uge!zYUbDFiz+MI>sZv^_C>{x_HcT0{Z}fDfg%BYKHHq_H^#=rDePwMIEF<% zGNnKqw^BH<_7&-%dq$q_lYfMCkme!bP9b;SStfHiU(Zg>ome_)am66peBP$d8$sz{ zIzwe1QVr+o9vwL6Ch#z!JL}dL1bmCki*02`5&84-z*sJ$sxGZLgm7A-jSoUjc_;={ zq!?wXxya?+jBN9e&UJAp@<#Usp}+Y8>Mox+)8j7cStG_4VSR019?e}nLm&D!gd&Eh zCZCX>#JPH|;M?HfZ+f85gHqtkG3kQ+yA?8Bo*X_Kk1fz8Te zgJX!8HWKl@5t^?v84NnVi14!|Q0E!l_`rm{O9@8*`XJy`vs*+1DNGY5 z6!2S`k!^+Lld||f)Bc}W7*lEhxGON}zydBoV>%XqSUNj}5TCQ0y z;6*hS^~k8j&YYsekWQl5gXKE0XhjCI5*Ms<{)IIoEr4`3kkV-@MWNPO0c*|zM6=kF z9Pf{Fx|><-jp^<6M^;=KmYOhknZ9+v>!fL!R?bE&1Sry~AAN32dn4swbr8BS?TuS; zxA!M@#~Z2J+|TB~CuX!`I;r1Q+8d<|pp())sgjG4aF~Pk+9-2)ggIcQ!j_-jQh%)} z{!J5wk(1owNWG5xASIbh8@RWUX$R7 zNsKpd&K@)%_-Tscdrz6sx56Isn8r}pJho7Wv6<|=Tb(Xb;dG(8tNIP63r`F=#p&`l z6%bdcty%2A&%XX&D<#ws`2kUUtJG{91r%opyhPit#E-=z3Gs#a2^A9yHiwFw_eXuW zqz9ob2=ee>xT2IXVApw(@4AqAf2>i~*o8}t-&-huNk2k-=nD?4fON4G?U^ElX^<^_ z3J#lb9i`)r04kM*iJ-2FE`cbzSB}bX?+)AKF z$Q92s8af}rIY%=0Bng<$=&0nW)u z!##qJ<3g;8%VO9Aa>ZJtj`Me#6_c`tYo1Ntl2kBb4&+uZ3ygw2o5N@fxYjg57^0AO zn=1(0PizKu0`YdnZ9+B^f3tj9eDhZ-+9}UwS7xYuJF7fuk3Lturv45$F9jv1LU#+H z*86Ow*)qwJI>6cV%;`P%&zvqhB>DT-Hg)pFOXr^ZUEou2aa`{}daU1TmFZpuVhlL8 z+;i2^GtfV`zE=FswtMdC&DpP{VKyA-Z%(RP>z_qnJ=18i-45v}a1 zRsK@4{wlLFxr4w<$<;T;M+SQ-fwO-tfz4uOe^=7+!|>VPPD;a_l_10o5d65kV9}G2 zx#ZS{E)z*vb9A0jw2SrV;Ji9HElIjoXc+%zt27bu3q_10Ss+uzA{&%&;45dpW?IyD zTu7RUo*FBc!Fzw7Wr{IH6j0bMX@}Mv_z&j8*N~KFTJqYz(VsD z%=h~fc<3kMe67+6JQP2`Re5O3I)&M?2Ln6zE7Pic)Pe<+xrE|9;>qHy=M07F$*Ho8 zIe1#Wx^WZfMmt7{gww=Rlo!~mqm(8rgZzh*z_GNzTmX3i$HF6d4zOE-)@WbjHOajO!zjaq-BgABl{MN5=e!7}xXgEj(g=Ea~`<@U2s&F^eI@ z77!8b;$tib@4KMN^ZS&M$24iil&8XUnvjQ8EkXx9K~O!(vAB{3ajg*l#Yp5W^J7U@ zEqj#NuMs1`Q{y*bBoACVBN^x92)()|0t9ECAI3#~BFVO7|8^Z*gzm*fej}+~UH@0| z;I`mw+aTOtNH4+4$7BiN%#7WR&recDXqa8)8jzT01<7Yom;I3QWpaM0r$}It>oXUE z>L6-W7zF_XRWFJ(0+~s-9umRmG}y;EN<$BT$@2|FopAJebZ17|O3^>$`i4Tg9$Oty zC^8BqWN*sMMpb#k8Q-wt^h+=CNq^$#fsx~fj~zX*Z}6ZJ0zc5$bzkvSgY3eO9%#ux zAwB(LM}{6L<(|+hr6Y*{6n?bav0%jRBwo&p(O~sLnj{0*05hU0GFp`TbiZ3mP_jHH zMr&7b?l$NMw?$zBDlIw|sDl!aU|hKhiq*FTA_eLUak8V~3|$&~20s}Ni9pKv>Nr(c zW{@3xL#;3a44+t&h4Z}>MX_=dBdDywcWpqDl&jZXt=>)iSwIG$g!t*11@7YQ{mHY& z(o(EA*d0&z3gx8hT6MTZlVKX8YRBcJ5%xmZDqwJdys~YR$Ojc^gJ-3XaaEz|0&McG zz0cL;TtddmsFZbmRhSHu-l7eWVd?B{i!Js^%QhWmvi?W?P-b~JVBJj?flRF2Efm%zd8SmXQr zkz?%($@*)ZzuU3)g`~bCJ~H$dlAhk|Et1Fa<@-|7@fFUsXT?;NNEdx(aG@$)nIez3 zgCOenbn(KVhd#`-lWZx!V#BYgOwX={Kadbk49)N4>~t5aiG7%qVw1Jf0VjXIFC|@A zZ`>abe0*8{lkY>C!5(#bOeU+q(F}s1S&aFZtjH#Zf5?a=!7j=i!Bheas7N@Hkwr@^ z48fl{$n!W{>+{nmOxO@#>JL4x$`}K8a4cl00X4eRNrd=vEOFs}hF_N324c?Ah4T`lI9kE~GeJe?tK&10G0l|6QPhnX z@kQb66yMF2YWa*ryZ{+zB+~u8gt#Z4uN*;tPo9&ng?QH1I=`B9{0+pjt3^{WY57YYGat829lC>OG|{>u_#6=iN9sy{pEI8gF_U3`xH z5jfj>qPNjp{MK1gKcY91c^v%)1;S)4R+&*~QguZwWg^x9{WqAfZX`;t{-lT@2wb z9ToigCql(n{r+OeXago(AtDZz>6Wb67v3Yc@q7}%BMj$tFaho&4vh*!ag^9~~Z{PgnR4>NcM+c7`Be;2F|AE6u zNKaovlN?PVKW6Uax7PfS|D-^Z$nQ^trf+vNaqaobB)zhJ*2GRP3EhsS?kHT5psjWL zThgpO_lHW-5(8IOda+B|bY4=on$k{nb7r3!qRd-9<$GY;sY(j|_k>WmpG{#B zL?65*?Ra;Z)PEvH5n&lZ7txaA#V5`bGcUWrjSVQSgoaB;g-rzh?`|LCx_ioF$EugL zuB7STm+J`KF-ZK<$<^=Wjzv`Nu8ub!3PaKg%I>(k;&~#m40fhd1LWwq1l6z#l8|!< z(KFgUv`HlrxA@ezKtiF>pDCb)TL^4Xd@Gm{(wsiWhoIO3dsw_+ytYes4|F z?@TN8YfAjq#}`7w`p}T?-kPFu-HlYkqd4o^Qly%)iqCXz8c(0X>9}F(T$5yEpRmS! zQ+h$CZ%f0a+*+{CZ-b7r+rlU`ct={jvcB1Nqp%Y8VgN37tvyb|qH7&8??~5g%m>## ze@DuekzK7z;J+*7+j3RNX^fy*Clq~OipeZQ(72PJy&|_cWof1n%o;`cEcVT*>X9`v9{6a4UQTur88=p9>|KItV-lcO8X!KjL zi-}H^xt`<4?08-1+4qqCm|E<4^zo*n764gvAatI=Bk+G;iY-n&l1EVced+((-nqxw zRaE)@?7dGqot^hdcpV^g4iG{}(jkCA2uK4_A^}1t;P`?xohI}p>5l0H3F(2c;_!!l_?WIb zwX4=zwQALC)o*cvcOo4=K?d}LX}Sli@YPb#=!rW_reQSU?!kh|ISw654Kzm;u{mkj z2h#~2*N|Un?t|%!nZ;X&XIY^g;xpMuyf^Pd2DiUtsJxH>-wq5!>ppqYmI2)hcGhnQ z0<7Efj0#sg{Rke)gPWS4iPUbu`K^0!aKkR4#tnOPkd5#Xe<6U!Z3CvwgfNL{GaGvGYs? zpfy#tJAu|heeUfeptVhEfSwy0Xw7)?vfB%^R{Lr>A9oUG?dOj=j*yI|5r2cQy|{Y% zf>#-3g>vyn86X~7isugFa4ZD~QSUJ(k?qOhqilNt7Two(G>FDF>K_e$Pi5KNZrB(= z9{qK&)i5WYvc7L!Pw&?AByBx(5gg+L;20-)zQoIGmwGuds&bCWSd=@P?B#2h+@Cz& z_01&TpK}F+`W(KwbEzMrN+P~uCrfJ~zI2|i9vSNNb~`T%bgAg&S6pU4US2tHtS@7s zeNA(MU5M4j9~X`GyDcE+gELkE(9(Nhvmii} z<%n=oc+D9QWi6+&q|j?|IN_w)w)MJD>Lvk61g!<+kJcIlv?8C`NNId~%0Th=pyz3` z5+?YjcWi}kQ#a4{f}2zA;^x}AgLf%tvd^!;-y?ww4SYkhz(=a`cGwCBtOTGJ|5i51 z4$!M!*{1bRyL10W*1z`S1Zgx871VF%M*51p&5sq#c1>A)WJ}vMTB8fQ>`0ibrKjK3VWjV%Osz|**yWn;w5M0%)AZTe?kAcpkPO}WU2W>PVlTA{^4Wh{7?;g zwj<_Uiv_a-)zk9HO;t7wM|(uMBg0WMS~wA3eEW=i!s&KX$A+i!z5;Ys^Zpp{qdxDc zP?+|{Kw(v>+6f~tXEn(V8Rl$Fe=cl<5u5Khbq}-v46CZf28LCM?IfucFs#}h8WkAU zns1GF>Qm+pP%sKGtQub^-8?>$vBb6|bzszDcz_Ijr^g!?rdr6RO*oG$Ro5>RLw~nAewXh491b z5jB0~g4)~>#e6k7FD_v(uNMbN*{hmw<9DG-hCj7Mc&KatRzKTbp#lI(dtA{~=C-# zi>wro>}9@k5=|xJDXF22JZXJ|Eg#UC>%$O{GJJuC)$5w{~!y$;LqyyJ*Rf zeJp`2t}Pf=wxu}YH;ary~enhuZ_Y`%RU}hJA$FHHI*K= zZ{{YIzI=RGl#Q_{2_+&UJJvUIlSRo31Rec@Lyn5^=JKD=(N`_|6FT}I9UXmvL89|0 zW{&`r&O_HdOAeF{dh1>Qr3-Z(l#IPg2C~63=W2nOzF!?PU4J@W#{PB8bp7d>vr07s z=Ey6V{`AZP0tUx|N~S-*iqBUYkDCrIeHpKv&&$syz@`^>T=Axxt7x3!ix^Vec`I$p zTYGdBjz1NBTWDxGH+5W$kE|vh0Lr}=haQJc4Zgkt*9gvJ!ydJ-1E8UIL2%w0#5cGg zgr<0SX?X4j^Jvlj=0(xmCOmgie-u3T!_vc>@!TaJDCF^>P}O<)bXbA!Ej;(b3Vd%a zJhQ_J{Bb#^&o6gINbQK{Zdsu&UQ#Y9ujGb2;9H9XraC?nYMskl z+ZFeMkn|m{J$f^li&a4^H>BB-O~CC(HUYOE*#z8vRQc#gY!dLlEz5}o+C4j_03#2; z?aC;C+n1(Y&A{zVg42uCrG?;xpS`pYoZf;jEd(cU>Ep{MMp`0pyJZ~}f!j|>muJ;O zaG8j}?P|=FSWcGsC@9Let;(gy&Vn8Uo>Gt?Z1z(M5`@iuN)tBwvhqtK2@#v!vO-;m zY1m+&eCMIQu2O)!l_8ih7C4BS;H#K8`**yYoo77l>Wd0dFs~$0I_?@J~@a-Fa zLiz4(Gn{t_ZiAWLsfK@`6wLJEzUIt;6<%IjUKg2Z3(Q!SQ!6y_3k!v7b7qv`!2kf? zU!QJKFaY1s*84tczwo!$7m^(hG3yJ-j)$1_g=9hTE^jDrj>L=)#8}pBlTCYN-0RXS zd96}u7=gYAj?GD!uPd5sr@7Y^%^Avd=P7}A(6P%~%U8ta+Cy`e<-7|&`_BvB+nsl1 zfFXw{aof2jN#6=N=Y`?s13$b%h~6>v0VtDB0_-Z;}BHOqUQrS1+%z2+_gKwu1|aFv^2?TOinKg6HMYXHLi{9J&YG zAWX1c*%MY${*F|~kb#N@xDv*^^PVHlcY*61lZf+O$&5KMDG#mW@Y91hbHw?-lk)Y2 zICIyRnCU`SsrMy3sFPNWN9cL^2D}zSR%jNHe=sR82_ny3D9za+eef1uaNjf zE^v47($Mn#r?02_00;1yIf&9$S@`L8^x8q-TGvB``HZ+styQrQ%0z_n(YjD3B9xET zg)$NA^wH$-ql1hlBBPHc$8hy(DmM}CKbDklE@U(@$S7p~AJ?c!mA20$=@;Pd>Y!05 zRh_p2%WDJRxcx*6j`OLI1#n;MAK>K)5Cz6H(}!?0Y}4-!ZuE5E-=~BiGSdPaS$W)T z5O2|wvtWD@jDMy+xF#{JeI}W{SKxFKa`;TL_q>>d@y{ejy)-aB3C3?t%AYS7pA;Am znb)8PD8uAR`OYLgt@@i`18FlIBnh0)0|z;L;+Cp72zGAZeN8T~DvULasD|$5`7!nvBBTnJkQx?_}hDXL8i?d_UYK@nO9yDg6t( zk11?EiaiBADz8R)1>Tk5@H$xu-WU8sl75YsG^i>`!o;P8<}hpF!Yu>^N20(G^T?nH z@M~l{@<8O<*p569?}-m7sF-%{(L)Mvme-vm2_d6c0sQKK?Dr(ZkiqSW93=crIgKA^ zgfxO21RvXx1Za`RH<1AG^3CX_?N4gIDKG64tbSq-+?S;HC)gd_YfJw=ZZ+LDZHI zKfrxXOM2eKGpm9qJ;;BcP866gBnzVOR4;$GPLv0ZAqS#*P~4=__E1uK7{y%`w9V{S zd@pEr+xA!nj5adFMsZsiVr+CX#SVi#mx??TqcaFisQklvbOvLx81_N#1`MQ99-YCE zfk=kv3?yOkhl2Z5O)CFBJkrL$#Q+C<;p6FN3UHv#MBD!}DgA0Ubf&MM zN0Ej`z<C7jZLv8%>1r=%oYJB{AsEuF7 zp+*wYf2pA+;WM~@o0Oj24Z^Qq8V?&u8tK1ninZ}nl0LH&st61KR+Nuj6&)ntsi=w$ z67W=1MUu==PbHOShR53YeN;siu~-{VOBEGO0c3$I)6%uPBiOmnJ$1XH(*r3Yiz{Am zdgvZas)7%=Qcnf`f~B0lHoZC}*v32jZQ00R8ybpQYv_eS>qr|`N+4}EC5FYEEkkxW z(gx%;M%uVK<)BY9hez7DIwjJ^ZO#jWK}Ll2WfZ#WNH7(ldZl!w}QOWG7_<1Hy~Mm1D;p8JlpbUn%uCmp~0+KE}G;Cz^N z=8gVhZZp~joO(BVw2k+sP0=>qo9??` z{#v@3h3*H^(mix@FEcY6D|X$D$QMO-7w`XV=V6CSYz%-D6evfr0_4bo4J7CC>>YRp zH{MHoQrGso?B~KZ!EbX*Iy<;nMdex{eh}QC)k9@6471VfZe0oL_qHooMs72NQ zsn4l_nl)g)HruFPZ#4O2f)i{D^3SD+!05LH`R7#qi>-R5|ZqM7A+7ELf!1rX@4PQrTr2k zhdJ?%H2o6fyvWD_vq{nHwnn4yvdqQl*LTjyhEw5tA&a8V6Nhs#7)2srr(r z`lL+PcupzXzLKW@%=^phla9Fy7IgIVZ(PV*&Q5@h76^L?q~C$fOCXuf=0A36fXgxn zb#x{UbYM0xIIv)7ea{fMaQa`dX$5D8BY*+mvKr$o7Nt44<4CB72YF~e#|O9_@{&NUrhs$#dw{9liY9r z{8s0RW9)wtS08D?l}>GUBUkP!a+&_QJbKPWXR=}3S(*6wqu`DZmm)ZFC-j4Vs&mJ& zI!U-Yp9ujIb#GewJ`=)f8vtRORLldWP`c3D&dugYnkt4({HSyJ-n6}%Ux0G!jcwcg zY5HC4?>V8#0O25?nxfa^9q@=#aXZJ{EX5B-f&*O6resR&h%cBu+Cd65A8t4Sh=`_q}<#qL%(7*WPYxE^Txc3S>UdWan#D9`N21G3f!882}5J)6&1vA3GNiuf8mdo{z&iL$?GE zr|o;?$H9PJ^R_*braz@K{NSk=WR0Cs-#Z(JLBjshmakpH{?hi5I2-y)+ehMTND>J@ zl2(2iWQ>QOrA(By~LIOPq14gARR6jK5XpBiDTUL`tN}*PFV#-P_PJ1eQuuq{@EK zZR|(4yZne!$B9O#+q)j95?Y`fVtk?^X|#pulO&Wsp@~Y;=c3_PY3ZrmApHgh&|%uB z`-ERf`qIXU(#9v#^mjX>jeN{_=WEwSl2rX<)JBr9_GHvXl4#?TY2|l88RY6pJ(trC$#ik}23ofa&uWYG3dAu<;&?7i-;kB7%UfH@ z`ry=TD03O_4==fJFnSwE)z;H$7`jxAu&CRGMUsY}i^h>8!g?+mN0JEZxpd|mGB=LO zFyr`#w0vde#!-1DuB$S{Whg|Gr1)>n*#Cn z*apVCK3?HB-TlW6E_avYvmY6D@gG0ZP4Ld#`-@7X2$?QLk}&bHEI=%gM2a8Fz>AUM zkz_0Pv24b1wt!L6Y~aVTnM?A`#xpy)Ph{y$*^=s77qp#t){V3oKj%H3X!dQM-?64q ztZUp!AxMZjUhcH58pA2#$~U@BgwZm^G=XL#57LBBWB~$&U*X{sSy=j##JYbXn|V`q ztSx<&Vb=W<*&a7#$9Ul6DYAUG$dzQ))r@LF_I%-u4mfEyfzG~Oz<7C?QbX{1gS)h__1LdzGj_WkmgA>^qV z@PC`7bE->eoc)?_@J-`&e;F{0J=o1)2q-*=I&06#KEwjX1+J+Ji%(?^V@Hyf{x;id zwv9uQaQ(O0K?fVx(<*IW&PxAx6s}{fyO(QT*OtF5uJHpcPZQT)(R_ADhg);^(XdcZ zGIeksMzR^ez#yM7!||QZa3taPD{+P+NgH2@GaO0y{fcI|$E42Fr0oBw8SbH7J?n1l z+ueHHZL)ZEWA#z7ndRi9&s8EZUW46V|u1XxA2O zI-1n>oh*GI>kJ11Itpz(o7FgW*Q2`6R6(G2mwfHJOX`Ba?_^mEpCczh1aU{-%516c3q@C9W4G%HWVcC7*?zMta=%(af< z>Ww%1cG$cm4S7)E8Sv8F4W?qwqk?gzv5zyB*g!h7Gv6d&8W2fGAlia z&hPT>tN!Y5n7x_-Q@_;i3mB*J3~BtYHCxRy&6AO`*Z@OY3zkixYVtPt`VI^9S-4wwtl>`(J=S!@0zqG(50eOit{^0l z%NxqXG`CJM1$jf6?de=&h9BPuQ`M@G&}jCW{Q+m%@S><+Ka#XB5w=&W;q}IHWk!L& z_|{eVoPcB)eKv}hx-odf3lM#AR-oDL>xoj)xi-X;+8*G=1BQQG+;4`j1I}cpU={HN z-n?bVf2duT=IyKGKTSvt#<%R=o%uMdd(YMY3bs!y8pXBnlpwBdFSq2l z$GeWP$f%>DutgdxGowlX#uop)ymob#PhVwg3JxKPvMt54cY%*)e` z;Esr-N9`;;ibk|JsszFB`s0YOa&SH+b{r5>Yx`bjuzusZC&%37%3SjD$GcYNhZfwp zD#obToghRafWjAu@Q>)MK_^;9mK{ zE)OlZ65L#K5Pm9IY;^qx-abHm0Y9y#o-qq1b zqI+ui=9KVB<;8g+Zb!MwwuN%lJt_8&s;!)mN5X(o)d&*4*u=$SjG##c4HRz}rH;=y z#wcB~C+^J7Z?(@pJM$ zPPScIy^HL8yK;Qq9*c%qW%jnaxA>%XSw1V&J5trWfmh^}LJbRB6`C4jP8?C)^rDu? zLhYP<&n_2n%nAoIm8DG+^W3MqYTKUL>R^`dP4WX`#UtqOw^LZF#;O1Cr@Ic@0h3-d zRXHr5ibK-o^AyP~%o#%E8>huY(mh$fy@a1^;;1bp3~S(bBw4;-VD%X1Qj>9gYOS4{ z?~MmUT~eABqP$LO;%4E~U30fr{R&oU8}r$!e? z|JR;Rjr^?gD4rGG%uQ+5^vc4P3f){V2&1~~0Z{8S{F_;|%7~Tn(2`6{wC_cQlZ=K@d)ebEgWu!jTHA-gXQ(&TwP^QY^Eg2b6 zHp=>tmY>9q4F>F3qkn#7UP1q5Ql#UD3gb6#n9aL9f{Z`i3Ag^zO=0bLV_;G3uL$BGpv0|~Q&$mRpONj9(u zJFV>6*u(qt_{;o`b3oMQ{HkN|!bKf(b(~oXAJq;es^ZqcEf%^)kwdwXrUnkW?G?Tv zA8!PoMsZj+Y+T>pqv(?MNLZDGIyfqMMW|u${1B|A7kZ;RV<^T!I>dG~1;FSrIxYCc zdgo%ObH(zLm!0t^3?+hTts~;bCW}E2LfwY`A$1}CaRbC7Ti?$UcaKlq(CtNs7}gQc zHPcFS>`#y%rk7^hpTIs;0vHky6EjK&S}t%7Gr>g?MAC2!B?nG245it^JEDSp3gD!D z>%d9+)8UZzs{<$LPtV-H4xFSvJ#$taI7xrzhMQFGDE%2=Z~=a(19!~`KXhOd{1B<< z6MhH>9UfhCusA23pW&e6b2{?p3eyjTINftJ436`%Ic+mz3JJ~GV_r-ld6I0wu++x8C>sK+{IEsZJY z>3r#*1$w{`DlaM@5$TC2LzdMyECbChLNXSE{w(Su};2m*x>Ynps3W82OdPN{e*JjJhDDq5XiEeP)cOy6odvqAZ1_*xEd_KvNT|(K=*suE8C|zegSV1UX`9( zRx1uz;K_-co@>NrYf__539Q)~uAgYl?*Owk+!==yw65VEGNgcpTf-iiai@}YA)Bq4 zv6Psl)XF_d*|3L>6quW0N7mgmbXkqdm10MQ{?&vzd=RJ(c<9B?=tQnwNQu(E^6cv2 zcFga`y}|2EL965mLbaSO_7mPyFP(aPM~K;(!tIIGfbjdud(_jk(6{G)^)xK@9nfKM zS5=;$FDxGdfYNHF@16~cerL0^?z!Q@4#8lLCIvb}nRr~*&?fiXR8nt4#^%EPYek#f zI%F3fJcsaI>J5I}kk+ajJK`c=?ZsNn9mcP6B{Cps5Ucp^WBF3BJKX&{c(E3>=pBs& zwP6FXw0OhRapq}mnbkb{wSj9o?_-g^Vd9LK5^XchN~$DeZ|Infg6Un=xQ(T^Ca!tn zZzFEWde4`jd9O`3yXGZ&z~@P6o}dJ>i-YEoK=UpRnrDas*~LNg3@{+OIA|UzH1Fb| zc}mF@AiEgNJJM>U`K<)$I>h>nizvk!p>M*ywC@|DlN?I}V=j@W2%ov)lTszb<&qdk z!Rl6`@#>y8L9@rbK7AvQGdr)^R6+x<52{T{qPSw`RoiNyudWEHZE0G#BB-{dVd4r@ z`(y@_(oBq3B|EFzx}LO3xTd3){jdTd!>UEQiwvfhs}j_kh!^$=6W}!oH;?nIf9x)x zv3GQzM2yhEEriA9NrT>z`t_)qliMC2Pbg{^7eox+yPiRF*CgBwUSYaGW7j7CBg09i zHc2&=L4aR-lSEwCCJdd+OJI*Qj-``JSTcbQu;JwO5;d;z9VTrfRZG5 z7yHg6eRn{hN$p*1$e0A%088M~oG`LfFDax((tQd@QrC46D}W@eUMH-8P?#ZlUBc+n zD;s`wN1N*shSv(!tqbz&lk{fve`!-}=1u**I0H1<-v$dmG{VGNb9TLcJtro(!?me$ zk^X+EhlA$?3*OWS8^Lw&YXXy`YAR|N3|-3ns0l}j<kWQ?KP;dNJ7so z$wc=i$7R`?o8j(rB%$S&WYz&@JOGlpH7R`~7!OJ4Rw3ZXcw`ulzfRKIg7L`Ac!UfY z55t7HJsJ;E3@nmvJRJPx_GmmD{N?s&JV;_ZZjZ)8N%PXXJsOWp#^Z}g`cJ#Xcu*UR zeK8sjk}@85?4a?m&)|{o+;~_9732Hu(~4yv-8-W3PzD9=+(qMI)zGKZ<3rOjtm0ri zEQ6NsjK)J57>~RDNXEmOgF@P?Qz+K&ipIlAK;d15@lXyKz@xpujE4~hGf?Iu*fL<| zYteXEhS463hcXz0ckiI_u+M0T@7#D;1})tkjfZ8>(%sQ`fJIa(e|`5E59)((DsgFnQ35} z0c+3@{8A7aFS zD^h8DBuRf7h#?IzWH>P-Dg8(!h9shUBoadsVjf8TRv#%tP; zvVH8@#&v7XBMp!z9A+Zyy4c5VVTGcT_4R}6`gZ)_dU~nR=Td zk5w(W1w-&e(mvOoY4Di8QvO9!Y$}5!V$f=M45HfPH{f9g=QBE)@4S;qQt2;}5bl{I z{QM$eUn%9`E&s2R((i-v=;8gZllBf%9^Sh1{y0gW3d%#8ddcv5NmBaBs5~U8_sOU{ zB$30DN#!ZzB(wr$NO{_RlK@7x$ka!9rar%my3A|(XOhxY+^a|$diVZJ(tfCs!<%&; zHz(!)PjU43}Ie&nh z!Wr|b%kqPRZ(?-+C~mI;jLGxli@8r|7Vo1@ln8*6-oEW{rK|yaJbo3Puju=zv2jnz z$8#>GpUs!|#ID9v!4Sog7tq!0NY=0s!MTwd$WXGRYJ%L#Xq1kxKHN(Vod zj+U2{fu-*FLGAQ#ao$wnh{(#bw@Glf`BBu)%4g`Ab7-cBPTCYbQ_=ofN6$?8bwYPT z^vu`iGn=ano+V4=DP&~F5X;+UyZBFiX7ZEl3wfSzV@fS(H z$FM4cj84znWd7H0HpQ5-xOMQyQNNe}Dj#=;N;sgHph15g(dDD_U2B=Ireyb)f$nyF z!XHDmQ}Z^jQ1LLkm#sQ`#p;pqFjsc1TD9yHkB9k^uH`HEJFQH~^W|rpeCFvZLrlys zwB=>hKk5j7RX&{vq2Msv)#G{V!Dw3_#(Hbl8`ZXOS^cvW`l@?cLq(QT*>>ppm*zR% z@O>MZz&8)!tSM*f)@~)%?n$wHcf+UEzsm9n#V@0BI*b?}IujcZfh#MDIGN`AJ8|*i zmZqVZl7-6$E*|VP33kU&o0Z;tM$g){{SI(_UYK|zk2_OyrCwbyW<%9g^mWlTn$qTr zgy23FQk4a`@c|Og8OEi3Ya=Pv%agjN*MAAME;;w{u2~?NO zH88{a#{!9kuI*HGZU6i7+WGmk;mT8)o$tTw&sHuwd3BdXeqFKboMkJ9>H8#H!IzzN z_VRAi_^J8C?qz8C>C4VI#nhgk&s?dGyH-rgmYno>*NgN0TJfOns~oTm@@sdb`MBjn zLtFYPM-%CN>qhr{o3i-8mTF<87p|r#!QlD-%E_|3Oriao-I;&N7~1V0uL{Mxix0Ow zjF{}oYLtld(^kJ?<+5Rdo5&=8+VYhvO>QJsBC_RYycAPW&G(e4=th#O&pY|dGhVX1 z`*iC7Lg_MPL|Sl6oVkh~>0ZA26~pSDkdIr|-F;>^Hi(*E-qn4E)m(dfl26l2BuN)D z+tMPYvAHatz&(f;&glA+RO6k zJ_lRtVFHGN2G7myp+LoJug|BmbnCxh>#o-&+tf2KbV=W)V0S`FKChlXgwf6BPU?LRZ6X9-fR2S zrWfn~Xls_l#bo7*JU7ouGn`|D@2nTv;r1)lqW$Rp=W9U19ar8&(8zfTi;cHl zBn>Mb5^O&1($*+=`|pxMcQT^a2Uk`OGUqz|QPX0XzTXZ2G)9o4SW7?iw>n2L}hz zJqicXz3L96`qSM)_pUpT>QB$yr&L7V)SsSNtvitFPY_`gd9ysbbWu|MVG?|`@GRD~ z=mkB!{p;m5i(Au{0rRUBzArbYx&|lAkPeS!83`Schpki`|(y zMRDVcGxP>|;g~11y($+D^@Sh@_ku2Lui}d`T!sRFV|T$;`I5Zj@P!?7d(Pj~v*3h_ zde-_MJ?nce>bbOM!=ZV{;zK)Lbq0>U^67rft6sCDW6j3Fi~2SU4)97~9@OL@OX~S_kiCmzdAYP!%Jb6Btopg6!`DCZZXD>lBp!w%TQkou zL>b}_B@S>cn%8D-VM^iNIB(`$PO4ic?4-RLo^Swz$n)vZz=-x{Hg@mvYcrydXw)($&`y<)dPw(MQ*^ zz%A!%?of}F6K)NceDv4uLwdJt+GL($v>zMSZGf}I{akh|@!dj-){iB;TS(FRv4<}U zEbGQ_NqK2(J^JHX)*Ne{^Y9bXQ?lybA@X2gIyPFg=^nRH%;s@hh#4n`?8GBZ4Q-C) zar-XUI;dKno}N{&OmIBbv$Gh!GWbL2Qm0M<_azM55a?F1!f;)%kJbVOhEbq@E@50< z=;OcR!k&wPn~^7oJ$t}FteuZh;HHU-B01%I^uG1$w`?r9ll$)SLW$(QyS(5I$BJxu z!JXW9UpCTx*Rl%#+?DBS`RA%Xtvk(j*j1Hr1?KtSK+(4Rb5|BYOXZ)tvIttL5S=TF zpr!K2J*&Jb_Ga|RwX7ezWVx+;wSt!3pLB5U!n2J2&BPa6+XrOXfZ5R^NO0(A$Z+{? z!b-)ExT3e?f=z(3Hh^oaDOQwgI`H&aKQv!LMY4YPX7&{?RQF)98VqNtZ_}p1O+_ny zX5}7__De@UecfDx9V=TezjjOiCN8v8Ss^Y30ey8b^b`d2)y2?L5YSf_QD+4u^qTT{ zQCu+ysAYY|#f3-c1?m6FsvnjjuA{qfVU>FM`cU(Z+W^tO9ED;w8A91WH3~m)*>>^Z zddY25_+E18;Q@|9-T7`8{-gzY2d=p`O>xU7mK4Vi#SS9j%{-pMRHRG54SjrSPQ5^B z4HmpB=I8|l?}|BkLBYFXj$S~NOt*D{O*k$Kv9?caY!1aCJqusoYz@{})Y! zHw1tmp2Ayh1@KbG((^mcN4^%1!^bmYRU;+HOrbHGDz+<6k<5iBH_AwfnbdsEH!-W~ zs*vz_<)QTAMqhJFUPbTAPrQ;{%E8!XyO7nwKlV;E_x8i`QwpRQEeF&q=f0|E!KJS` z>>!kaRfjr}|MUPWbmH3i#o~jN#URjVtWOw!D8eSjOpJdm67clBl*>wtw^H=)rA;pG zm*NX4Pv4R{?DF)@=IOf{4T(`$?IgM*NUAC1Fm7G-6_7Vz!nu6>l>9P0>!?!G|CP9) z5Rmiife5g(Hr8gao*R3HLZ7hKvc^LANnaQENDfZjL_ip%C(IH+BA$Sw3POTvRStud8+QduFJd^qVM9eX)PqG573&&Hd|b_(>G%(%MVAYM}+QW%vMtJIOdj z%LzQWu5a@~0!qjOPff~gh8lV795bwmiIZ}kxr?Mq`K<{+qzkb%ZrK(ZUs26Xk%H=} zb(17ot$S_0#Do=~_Sa_6%4IgtZPsM+9f%m!{#Dww+&+5cZzPFG=`)kNABN{NkQ` zeNy@W{LVExH~CR$!EgOot(jT%$n^?=#>8!o%5CpY(i@U9sPK0DHw7zte-deNqr@O%STTB7N$lL?iwQ3p;GRN}rb zBx&IzNr0p!iSR!n;h$&?^5b9PhE-i`4XPgOz(sun^Q{Ad+%#kw785F^1+6zHWK61X zNxDPWUnT+O+a1FGQm$J^AtoHcZc0j@K}?4*jKVxEpH)qpt!3oyvgq}ENH)*0o8{ov z)X_lB_lZmwN&!zuX(m&OJGCUy%$uY88cF!SISKA-BoWTda$j3#E%D>06Yx!6VZy27 zg9Zs{^)s+lyDMOy@kZJj0DWzV5mo_aN-?A+Sp~hd#VyvDBdMs3IOQWlT5=hZw1xw^ zC`qXLw0uS-L)_m!o0M)3GHkXDO~QHDzx&!LMc z4S5uI^4yQ^wm4WwLf&n0u#jZ1+?G`SCJYv3*kJh^4VL5JfS_+*OiF(T2Mf%YYMzO( zZc+x{AgD80J~V74%*M$x?~CF?aij2@Ba%{*ehEH0M&ZM2vQ(uxfF02ih!{Qdq_6i-k@7&5XN5A;G0va?~S`}VLLk5j}EdkN;MWGSW zc(G2c&S~nV3wvy1#}d+ZI~)}C6Uj%WEY>XQ_^=_vYNBQwFRX2P?4G1NBY-HzX%6!H z2Og9h8OOTH++o`vSXQtWbb$mIjKXnc-EyFXeqcXhl! znX#W)XLohHU(UgD4MdwCNJ^gwzIgIXd>{s+Zby^9o1{3U!aebU%$q-CT&)$ixh_7; zLae&Qy0CG{Et)ZdTH4yypmQGK`H1gcEdMQ(G}32@!CBqf1=+cB%2(DCvMam!??#K5RM z-x^9KG*@eY1<7E6^crUi8dT9iHvU5yfEKLD2X4f;& zpr0flgdZNhpuoQ+<>}Sgu9DW<>SNX?z1r)(=%W6Oqc-V!0XgcaI+bj~Uq=`^U_vv!P_ZsR@+WT3>^_L4q1$$Y*LHL7m$@p%M6ZQGyIfTvn%7KQ&B(4LYzr;$y!X zlx7!%C-w&hqu_j(#+u!n476q#PDqgB@V0kFimm%Ik90N2SB4Ym)iqRx^LNrvJ)|Yp zn4EsoLxb_B6QdtnhxxIEwLZhZ4T+g9k6*@T{!Gc^mpzlrI4J%~k3EwdGB=-RP0-+T ziXXop#}y5}V)0O*sbW3;q;Rw$BJa5vIKJItHaw@m@z&zJVMiL1DgY9nZc5=mj zo`;1x$FTyJ#AmH&JtKl~(8p;Wrv^iVYFU%?1_m?{JI>$2@@jqmMSUG7FI(XQlT|1b zUV^ie%BjBj9m{!?4xY&nv#(C|D2v;^jAPGQR=6(nO!n`ZG!N11GEQjP-k1{WS0`2D zB`TXWLe>J=Cf>bZBj2Xbp8F4*HmJRjWz;1Vr*kOp6TW>Q#P{xW(w=!Y-t#o!!nrPO+dI7U1NWK^el3Ut!a&CeG#+b( z3$fUO@8flXd68`-rsor4ov=owljxKp3lUwHPM*=21$);i4)YlWF%-H!Z9C8cXXwnw zHy7TJpBviIe$>ra00|H991&dRO;VM5tCBGlPHfDwHYUw#%z}{X)7drl2Cgs+-6z~))zBtX4%Ivv|awROm* z2Q@b<>Y~CrPtX$cQ;IB{g_EDP{TEz-;JKpSIB3fgR97CRW^%3OcyhwGRQ0KJ{6t$$ zl9Z{uB`xn`md?@?AY*1dgRyZ-%G@N=rxFynH7!qz8%AxVC7l6n)*zl`PR~D>l zb<$_!G7!hfl?4@OAW_Ny1=T_VTCaRQ-G5fjy{d&LRaoU|+^cHDsr%wO!g`RJq(!`S zLdPiB7L!zahx#-83ZHjKtTodV4tDQM)32c^m5%7J>+7GoMrabcGaWxQXoQ{NemMxYC}jckhK<0&d*`#Dju&Q?w)@ib{`8FM6jPVx9V@>> z5Cxndl6-w%jCn~Cg6@kkFG;dRzb~D6f9faA%CG~c`%?~_6wBP=x;~I{MC{;2BaetR zp3Ihxem+bE5JU}rKJ39*A5buDX{`rieIO0z!@0WnL3QfRo)1$4%~3_FLB-)b~;Q^ zCJoBE9+E^YAC5ulNmB2_>9jpeG$f(*;dJkP>~wgd82L&1{GSff5E7&%mmo=NIGhfX zgsPv&0_deG(PDp=mVSW*=QCI&Djq3m-qtL}Mu90>12TGH^;nUh*9rssvy|J{H|o5H z(5jU-q76Tup7uX^;sY6Q4;{`uNvM1*2G}JD_ZIb7r&c5xKaZuA$5RjPtPC4JkEiA3 zA-pZ${~Wcho;G~0FVHnLf+QllLoLD|$CVI2*c@ArRTJg|;a9r0vEfY6LFOHxM}(udT5_Q)x#>P z`3Rq)NU;c0?4e7GFvT9avBofH;skHP4JXmEA6>;+^ zQFQ`(LpaJx+tX?K3{?3Qsfm-do%!}KiwDPw=yTzdb$^VF%lD8<1>WH#sr~8L;Uwws zr(;BAl92jzT6rdrsthCb8IdY;KwwF>_h~vKn1j%|oijEp?PUBYO4F3}4kT%xwokF~ zPm-peOF0f!)GmTMf=8w3cOJFN>%{|6o;R^#ZKaE4u{Qp`#5H$h7BQh-IeJl3k%Wk= zVhlc-frzWJ>5h~@5+bfrs5u?z5^3=oLK=mBP#nZ-6k};U^jRFlH?gp(o?BOR$g#F# zA86U7O@EBK6b{PceYsz1@sapx`p`bnqx_)z9x0LLTy!2O@l7%Gm`6%{6QRfA8|?oN D1qkIR diff --git a/packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json b/packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json deleted file mode 100644 index 17b4598a92d2..000000000000 --- a/packages/gapic-generator/generated_showcase/showcase_grpc_service_config.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "methodConfig": [ - { - "name": [ - {"service": "google.showcase.v1beta1.Echo"}, - {"service": "google.showcase.v1beta1.Messaging"}, - {"service": "google.showcase.v1beta1.SequenceService"} - ], - "timeout": "5s" - }, - { - "name": [ - { - "service": "google.showcase.v1beta1.Echo", - "method": "Echo" - }, - { - "service": "google.showcase.v1beta1.Echo", - "method": "Expand" - }, - { - "service": "google.showcase.v1beta1.Echo", - "method": "PagedExpand" - }, - { - "service": "google.showcase.v1beta1.Messaging", - "method": "GetRoom" - }, - { - "service": "google.showcase.v1beta1.Messaging", - "method": "ListRooms" - }, - { - "service": "google.showcase.v1beta1.Messaging", - "method": "GetBlurb" - }, - { - "service": "google.showcase.v1beta1.Messaging", - "method": "ListBlurbs" - }, - { - "service": "google.showcase.v1beta1.Messaging", - "method": "SearchBlurbs" - }, - { - "service": "google.showcase.v1beta1.Messaging", - "method": "Connect" - }, - { - "service": "google.showcase.v1beta1.SequenceService", - "method": "AttemptSequence" - } - ], - "retryPolicy": { - "maxAttempts": 3, - "maxBackoff": "3s", - "initialBackoff": "0.1s", - "backoffMultiplier": 2, - "retryableStatusCodes": [ - "UNAVAILABLE", - "UNKNOWN" - ] - }, - "timeout": "10s" - }, - { - "name": [ - { - "service": "google.showcase.v1beta1.Identity", - "method": "GetUser" - }, - { - "service": "google.showcase.v1beta1.Identity", - "method": "ListUsers" - } - ], - "retryPolicy": { - "maxAttempts": 5, - "maxBackoff": "3s", - "initialBackoff": "0.2s", - "backoffMultiplier": 2, - "retryableStatusCodes": [ - "UNAVAILABLE", - "UNKNOWN" - ] - }, - "timeout": "5s" - } - ] -} diff --git a/packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml b/packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml deleted file mode 100644 index a28ee5b2f64a..000000000000 --- a/packages/gapic-generator/generated_showcase/showcase_v1beta1.yaml +++ /dev/null @@ -1,91 +0,0 @@ -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.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. - -type: google.api.Service -config_version: 3 -name: showcase.googleapis.com -title: Client Libraries Showcase API - -apis: -- name: google.showcase.v1beta1.Compliance -- name: google.showcase.v1beta1.Echo -- name: google.showcase.v1beta1.Identity -- name: google.showcase.v1beta1.Messaging -- name: google.showcase.v1beta1.SequenceService -- name: google.showcase.v1beta1.Testing -# Mix-in services -- name: 'google.cloud.location.Locations' -- name: 'google.iam.v1.IAMPolicy' -- name: 'google.longrunning.Operations' - -documentation: - summary: |- - Showcase represents both a model API and an integration testing surface for - client library generator consumption. - -backend: - rules: - - selector: 'google.cloud.location.Locations.*' - deadline: 60.0 - - selector: 'google.iam.v1.IAMPolicy.*' - deadline: 60.0 - - selector: 'google.longrunning.Operations.*' - deadline: 60.0 - -http: - rules: - - selector: google.cloud.location.Locations.ListLocations - get: '/v1beta1/{name=projects/*}/locations' - - selector: google.cloud.location.Locations.GetLocation - get: '/v1beta1/{name=projects/*/locations/*}' - - selector: google.iam.v1.IAMPolicy.SetIamPolicy - post: '/v1beta1/{resource=users/*}:setIamPolicy' - body: '*' - additional_bindings: - - post: '/v1beta1/{resource=rooms/*}:setIamPolicy' - body: '*' - - post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy' - body: '*' - - post: '/v1beta1/{resource=sequences/*}:setIamPolicy' - body: '*' - - selector: google.iam.v1.IAMPolicy.GetIamPolicy - get: '/v1beta1/{resource=users/*}:getIamPolicy' - additional_bindings: - - get: '/v1beta1/{resource=rooms/*}:getIamPolicy' - - get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy' - - get: '/v1beta1/{resource=sequences/*}:getIamPolicy' - - selector: google.iam.v1.IAMPolicy.TestIamPermissions - post: '/v1beta1/{resource=users/*}:testIamPermissions' - body: '*' - additional_bindings: - - post: '/v1beta1/{resource=rooms/*}:testIamPermissions' - body: '*' - - post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions' - body: '*' - - post: '/v1beta1/{resource=sequences/*}:testIamPermissions' - body: '*' - - selector: google.longrunning.Operations.ListOperations - get: '/v1beta1/operations' - - selector: google.longrunning.Operations.GetOperation - get: '/v1beta1/{name=operations/**}' - - selector: google.longrunning.Operations.DeleteOperation - delete: '/v1beta1/{name=operations/**}' - - selector: google.longrunning.Operations.CancelOperation - post: '/v1beta1/{name=operations/**}:cancel' -publishing: - method_settings: - - selector: google.showcase.v1beta1.Echo.Echo - auto_populated_fields: - - request_id - - other_request_id diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt deleted file mode 100644 index 0ce4b3d6e6f5..000000000000 --- a/packages/gapic-generator/generated_showcase/testing/constraints-3.10.txt +++ /dev/null @@ -1,12 +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, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.25.0 -google-auth==2.14.1 -grpcio==1.59.0 -proto-plus==1.26.1 -protobuf==6.33.5 -grpc-google-iam-v1==0.14.2 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt deleted file mode 100644 index 1cd0c5a2c3d4..000000000000 --- a/packages/gapic-generator/generated_showcase/testing/constraints-3.11.txt +++ /dev/null @@ -1,11 +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 -google-auth -grpcio -proto-plus -protobuf -# cryptography is a direct dependency of google-auth -cryptography -grpc-google-iam-v1 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt deleted file mode 100644 index 1cd0c5a2c3d4..000000000000 --- a/packages/gapic-generator/generated_showcase/testing/constraints-3.12.txt +++ /dev/null @@ -1,11 +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 -google-auth -grpcio -proto-plus -protobuf -# cryptography is a direct dependency of google-auth -cryptography -grpc-google-iam-v1 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt deleted file mode 100644 index f85022a2fb62..000000000000 --- a/packages/gapic-generator/generated_showcase/testing/constraints-3.13.txt +++ /dev/null @@ -1,13 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -grpcio>=1 -proto-plus>=1 -protobuf>=7 -grpc-google-iam-v1>=0 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt deleted file mode 100644 index f85022a2fb62..000000000000 --- a/packages/gapic-generator/generated_showcase/testing/constraints-3.14.txt +++ /dev/null @@ -1,13 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -grpcio>=1 -proto-plus>=1 -protobuf>=7 -grpc-google-iam-v1>=0 diff --git a/packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt b/packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt deleted file mode 100644 index f85022a2fb62..000000000000 --- a/packages/gapic-generator/generated_showcase/testing/constraints-3.15.txt +++ /dev/null @@ -1,13 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -grpcio>=1 -proto-plus>=1 -protobuf>=7 -grpc-google-iam-v1>=0 diff --git a/packages/gapic-generator/generated_showcase/tests/__init__.py b/packages/gapic-generator/generated_showcase/tests/__init__.py deleted file mode 100644 index c4290ea03f84..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/__init__.py b/packages/gapic-generator/generated_showcase/tests/unit/__init__.py deleted file mode 100644 index c4290ea03f84..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py deleted file mode 100644 index c4290ea03f84..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py deleted file mode 100644 index c4290ea03f84..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py deleted file mode 100644 index 35e420746ddf..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py +++ /dev/null @@ -1,9408 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 asyncio -import re -from unittest import mock -from unittest.mock import AsyncMock - -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 collections.abc import Sequence, Mapping -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 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.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.showcase_v1beta1.services.echo import EchoAsyncClient -from google.showcase_v1beta1.services.echo import EchoClient -from google.showcase_v1beta1.services.echo import pagers -from google.showcase_v1beta1.services.echo import transports -from google.showcase_v1beta1.types import echo as gs_echo -import google.api_core.operation_async as operation_async # type: ignore -import google.auth -import google.protobuf.any_pb2 as any_pb2 # type: ignore -import google.protobuf.duration_pb2 as duration_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -import google.rpc.status_pb2 as status_pb2 # type: ignore -try: - from google.api_core import version_header - HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - HAS_GOOGLE_API_CORE_VERSION_HEADER = False - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) -_UUID4_RE = re.compile(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}") - - -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 - - -@pytest.fixture(autouse=True) -def set_event_loop(): - try: - asyncio.get_running_loop() - yield - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - yield - finally: - loop.close() - asyncio.set_event_loop(None) - - -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" - custom_endpoint = ".custom" - - assert EchoClient._get_default_mtls_endpoint(None) is None - assert EchoClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EchoClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EchoClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EchoClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EchoClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - assert EchoClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint - -def test__read_environment_variables(): - assert EchoClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EchoClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EchoClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with pytest.raises(ValueError) as excinfo: - EchoClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - else: - assert EchoClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert EchoClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EchoClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EchoClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EchoClient._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 EchoClient._read_environment_variables() == (False, "auto", "foo.com") - - -def test_use_client_cert_effective(): - # Test case 1: Test when `should_use_client_cert` returns True. - # We mock the `should_use_client_cert` function to simulate a scenario where - # the google-auth library supports automatic mTLS and determines that a - # client certificate should be used. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): - assert EchoClient._use_client_cert_effective() is True - - # Test case 2: Test when `should_use_client_cert` returns False. - # We mock the `should_use_client_cert` function to simulate a scenario where - # the google-auth library supports automatic mTLS and determines that a - # client certificate should NOT be used. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): - assert EchoClient._use_client_cert_effective() is False - - # Test case 3: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EchoClient._use_client_cert_effective() is True - - # Test case 4: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EchoClient._use_client_cert_effective() is False - - # Test case 5: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): - assert EchoClient._use_client_cert_effective() is True - - # Test case 6: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): - assert EchoClient._use_client_cert_effective() is False - - # Test case 7: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): - assert EchoClient._use_client_cert_effective() is True - - # Test case 8: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): - assert EchoClient._use_client_cert_effective() is False - - # Test case 9: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. - # In this case, the method should return False, which is the default value. - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, clear=True): - assert EchoClient._use_client_cert_effective() is False - - # Test case 10: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. - # The method should raise a ValueError as the environment variable must be either - # "true" or "false". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): - with pytest.raises(ValueError): - EchoClient._use_client_cert_effective() - - # Test case 11: Test when `should_use_client_cert` is available and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. - # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): - assert EchoClient._use_client_cert_effective() is False - - # Test case 12: Test when `should_use_client_cert` is available and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, - # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): - with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): - assert EchoClient._use_client_cert_effective() is False - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert EchoClient._get_client_cert_source(None, False) is None - assert EchoClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EchoClient._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 EchoClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EchoClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) -@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EchoClient._DEFAULT_UNIVERSE - default_endpoint = EchoClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EchoClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EchoClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EchoClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EchoClient.DEFAULT_MTLS_ENDPOINT - assert EchoClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EchoClient._get_api_endpoint(None, None, default_universe, "always") == EchoClient.DEFAULT_MTLS_ENDPOINT - assert EchoClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EchoClient.DEFAULT_MTLS_ENDPOINT - assert EchoClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EchoClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EchoClient._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." - -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_echo_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__' - ) as call: - client.echo() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_echo_error_details_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.echo_error_details), - '__call__' - ) as call: - client.echo_error_details() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_expand_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__' - ) as call: - client.expand() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_collect_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect), - '__call__' - ) as call: - client.collect() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_chat_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.chat), - '__call__' - ) as call: - client.chat() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_paged_expand_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__' - ) as call: - client.paged_expand() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_paged_expand_legacy_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__' - ) as call: - client.paged_expand_legacy() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_paged_expand_legacy_mapped_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__' - ) as call: - client.paged_expand_legacy_mapped() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_wait_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.wait), - '__call__' - ) as call: - client.wait() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") -@pytest.mark.parametrize("transport_name", [ - ("grpc"), - ("rest"), -]) -def test_block_api_version_header(transport_name): - client = EchoClient(credentials=ga_credentials.AnonymousCredentials(), transport=transport_name) - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.19.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 19): - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.block), - '__call__' - ) as call: - client.block() - - # Establish that the api version header was sent. - _, _, kw = call.mock_calls[0] - assert kw['metadata'][0] == (version_header.API_VERSION_METADATA_KEY, "v1_20240408") - else: - pytest.skip("google-api-core>=2.19.0 is required for `google.api_core.version_header`") - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert EchoClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EchoClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EchoClient._get_universe_domain(None, None) == EchoClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EchoClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = EchoClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = EchoClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -def test__setup_request_id(): - class MockRequest: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - def __contains__(self, key): - return hasattr(self, key) - - class MockProtoRequest: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - def HasField(self, key): - return hasattr(self, key) - - # Test with proto3 optional field not in request - request = MockRequest() - EchoClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with proto3 optional field already in request - request = MockRequest(request_id="already_set") - EchoClient._setup_request_id(request, "request_id", True) - assert request.request_id == "already_set" - - # Test with non-proto3 optional field empty - request = MockRequest(request_id="") - EchoClient._setup_request_id(request, "request_id", False) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with non-proto3 optional field already set - request = MockRequest(request_id="already_set") - EchoClient._setup_request_id(request, "request_id", False) - assert request.request_id == "already_set" - - # Test with proto3 optional field not in request (MockProtoRequest) - request = MockProtoRequest() - EchoClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with proto3 optional field already in request (MockProtoRequest) - request = MockProtoRequest(request_id="already_set") - EchoClient._setup_request_id(request, "request_id", True) - assert request.request_id == "already_set" - - # Test with ValueError - class MockValueErrorRequest: - def HasField(self, key): - raise ValueError("Mismatched field") - def __contains__(self, key): - return hasattr(self, key) - - request = MockValueErrorRequest() - EchoClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with dict and proto3 optional field not in request - request = {} - EchoClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) - - # Test with dict and proto3 optional field already in request - request = {"request_id": "already_set"} - EchoClient._setup_request_id(request, "request_id", True) - assert request["request_id"] == "already_set" - - # Test with dict and non-proto3 optional field empty - request = {"request_id": ""} - EchoClient._setup_request_id(request, "request_id", False) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) - - # Test with dict and non-proto3 optional field already set - request = {"request_id": "already_set"} - EchoClient._setup_request_id(request, "request_id", False) - assert request["request_id"] == "already_set" - -@pytest.mark.parametrize("client_class,transport_name", [ - (EchoClient, "grpc"), - (EchoAsyncClient, "grpc_asyncio"), - (EchoClient, "rest"), -]) -def test_echo_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 == ( - 'localhost:7469' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://localhost:7469' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EchoGrpcTransport, "grpc"), - (transports.EchoGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EchoRestTransport, "rest"), -]) -def test_echo_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", [ - (EchoClient, "grpc"), - (EchoAsyncClient, "grpc_asyncio"), - (EchoClient, "rest"), -]) -def test_echo_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 == ( - 'localhost:7469' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://localhost:7469' - ) - - -def test_echo_client_get_transport_class(): - transport = EchoClient.get_transport_class() - available_transports = [ - transports.EchoGrpcTransport, - transports.EchoRestTransport, - ] - assert transport in available_transports - - transport = EchoClient.get_transport_class("grpc") - assert transport == transports.EchoGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EchoClient, transports.EchoGrpcTransport, "grpc"), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio"), - (EchoClient, transports.EchoRestTransport, "rest"), -]) -@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) -@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) -def test_echo_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(EchoClient, '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(EchoClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EchoClient, transports.EchoGrpcTransport, "grpc", "true"), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EchoClient, transports.EchoGrpcTransport, "grpc", "false"), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EchoClient, transports.EchoRestTransport, "rest", "true"), - (EchoClient, transports.EchoRestTransport, "rest", "false"), -]) -@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) -@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_echo_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", [ - EchoClient, EchoAsyncClient -]) -@mock.patch.object(EchoClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EchoClient)) -@mock.patch.object(EchoAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EchoAsyncClient)) -def test_echo_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. - test_cases = [ - ( - # With workloads present in config, mTLS is enabled. - { - "version": 1, - "cert_configs": { - "workload": { - "cert_path": "path/to/cert/file", - "key_path": "path/to/key/file", - } - }, - }, - mock_client_cert_source, - ), - ( - # With workloads not present in config, mTLS is disabled. - { - "version": 1, - "cert_configs": {}, - }, - None, - ), - ] - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - for config_data, expected_cert_source in test_cases: - env = os.environ.copy() - env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) - with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source - - # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). - test_cases = [ - ( - # With workloads present in config, mTLS is enabled. - { - "version": 1, - "cert_configs": { - "workload": { - "cert_path": "path/to/cert/file", - "key_path": "path/to/key/file", - } - }, - }, - mock_client_cert_source, - ), - ( - # With workloads not present in config, mTLS is disabled. - { - "version": 1, - "cert_configs": {}, - }, - None, - ), - ] - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - for config_data, expected_cert_source in test_cases: - env = os.environ.copy() - env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") - with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - -@pytest.mark.parametrize("client_class", [ - EchoClient, EchoAsyncClient -]) -@mock.patch.object(EchoClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoClient)) -@mock.patch.object(EchoAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EchoAsyncClient)) -def test_echo_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EchoClient._DEFAULT_UNIVERSE - default_endpoint = EchoClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EchoClient._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", [ - (EchoClient, transports.EchoGrpcTransport, "grpc"), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio"), - (EchoClient, transports.EchoRestTransport, "rest"), -]) -def test_echo_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", [ - (EchoClient, transports.EchoGrpcTransport, "grpc", grpc_helpers), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EchoClient, transports.EchoRestTransport, "rest", None), -]) -def test_echo_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_echo_client_client_options_from_dict(): - with mock.patch('google.showcase_v1beta1.services.echo.transports.EchoGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EchoClient( - 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", [ - (EchoClient, transports.EchoGrpcTransport, "grpc", grpc_helpers), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_echo_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( - "localhost:7469", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="localhost:7469", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - # Pure protobuf messages (non-proto-plus) require keyword arguments. - gs_echo.EchoRequest(**{ - "request_id": "explicit value for autopopulate-able field", - "other_request_id": "explicit value for autopopulate-able field", - }), - { - "request_id": "explicit value for autopopulate-able field", - "other_request_id": "explicit value for autopopulate-able field", - }, -]) -def test_echo(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - ) - response = client.echo(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.EchoRequest() - request.request_id = "explicit value for autopopulate-able field" - request.other_request_id = "explicit value for autopopulate-able field" - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoResponse) - assert response.content == 'content_value' - assert response.severity == gs_echo.Severity.NECESSARY - assert response.request_id == 'request_id_value' - assert response.other_request_id == 'other_request_id_value' - - -def test_echo_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 = EchoClient( - 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 = gs_echo.EchoRequest( - content='content_value', - header='header_value', - other_header='other_header_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.echo(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoRequest( - content='content_value', - header='header_value', - other_header='other_header_value', - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - -def test_echo_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 = EchoClient( - 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.echo 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.echo] = mock_rpc - request = {} - client.echo(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.echo(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_echo_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 = EchoAsyncClient( - 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.echo 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.echo] = mock_rpc - - request = {} - await client.echo(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.echo(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 -@pytest.mark.parametrize("request_type", [ - # Pure protobuf messages (non-proto-plus) require keyword arguments. - gs_echo.EchoRequest(**{ "request_id": "explicit value for autopopulate-able field", "other_request_id": "explicit value for autopopulate-able field", }), - { "request_id": "explicit value for autopopulate-able field", "other_request_id": "explicit value for autopopulate-able field", }, -]) -async def test_echo_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - response = await client.echo(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.EchoRequest() - request.request_id = "explicit value for autopopulate-able field" - request.other_request_id = "explicit value for autopopulate-able field" - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoResponse) - assert response.content == 'content_value' - assert response.severity == gs_echo.Severity.NECESSARY - assert response.request_id == 'request_id_value' - assert response.other_request_id == 'other_request_id_value' - - -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoErrorDetailsRequest(), - {}, -]) -def test_echo_error_details(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.echo_error_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.EchoErrorDetailsResponse( - ) - response = client.echo_error_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.EchoErrorDetailsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoErrorDetailsResponse) - - -def test_echo_error_details_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 = EchoClient( - 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 = gs_echo.EchoErrorDetailsRequest( - single_detail_text='single_detail_text_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.echo_error_details), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.echo_error_details(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoErrorDetailsRequest( - single_detail_text='single_detail_text_value', - ) - assert args[0] == request_msg - -def test_echo_error_details_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 = EchoClient( - 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.echo_error_details 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.echo_error_details] = mock_rpc - request = {} - client.echo_error_details(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.echo_error_details(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_echo_error_details_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 = EchoAsyncClient( - 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.echo_error_details 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.echo_error_details] = mock_rpc - - request = {} - await client.echo_error_details(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.echo_error_details(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoErrorDetailsRequest(), - {}, -]) -async def test_echo_error_details_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.echo_error_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoErrorDetailsResponse( - )) - response = await client.echo_error_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.EchoErrorDetailsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoErrorDetailsResponse) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.ExpandRequest(), - {}, -]) -def test_expand(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([gs_echo.EchoResponse()]) - response = client.expand(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.ExpandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, gs_echo.EchoResponse) - - -def test_expand_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 = EchoClient( - 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 = gs_echo.ExpandRequest( - content='content_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.expand(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.ExpandRequest( - content='content_value', - ) - assert args[0] == request_msg - -def test_expand_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 = EchoClient( - 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.expand 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.expand] = mock_rpc - request = {} - client.expand(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.expand(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_expand_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 = EchoAsyncClient( - 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.expand 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.expand] = mock_rpc - - request = {} - await client.expand(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.expand(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.ExpandRequest(), - {}, -]) -async def test_expand_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[gs_echo.EchoResponse()]) - response = await client.expand(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.ExpandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, gs_echo.EchoResponse) - - -def test_expand_flattened(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([gs_echo.EchoResponse()]) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.expand( - content='content_value', - error=status_pb2.Status(code=411), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].content - mock_val = 'content_value' - assert arg == mock_val - arg = args[0].error - mock_val = status_pb2.Status(code=411) - assert arg == mock_val - - -def test_expand_flattened_error(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.expand( - gs_echo.ExpandRequest(), - content='content_value', - error=status_pb2.Status(code=411), - ) - -@pytest.mark.asyncio -async def test_expand_flattened_async(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([gs_echo.EchoResponse()]) - - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.expand( - content='content_value', - error=status_pb2.Status(code=411), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].content - mock_val = 'content_value' - assert arg == mock_val - arg = args[0].error - mock_val = status_pb2.Status(code=411) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_expand_flattened_error_async(): - client = EchoAsyncClient( - 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.expand( - gs_echo.ExpandRequest(), - content='content_value', - error=status_pb2.Status(code=411), - ) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoRequest(), - {}, -]) -def test_collect(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - ) - response = client.collect(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoResponse) - assert response.content == 'content_value' - assert response.severity == gs_echo.Severity.NECESSARY - assert response.request_id == 'request_id_value' - assert response.other_request_id == 'other_request_id_value' - -def test_collect_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 = EchoClient( - 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.collect 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.collect] = mock_rpc - request = [{}] - client.collect(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.collect(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_collect_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 = EchoAsyncClient( - 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.collect 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.collect] = mock_rpc - - request = [{}] - await client.collect(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.collect(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoRequest(), - {}, -]) -async def test_collect_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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 - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeStreamUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - response = await (await client.collect(iter(requests))) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoResponse) - assert response.content == 'content_value' - assert response.severity == gs_echo.Severity.NECESSARY - assert response.request_id == 'request_id_value' - assert response.other_request_id == 'other_request_id_value' - - -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoRequest(), - {}, -]) -def test_chat(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.chat), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([gs_echo.EchoResponse()]) - response = client.chat(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, gs_echo.EchoResponse) - -def test_chat_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 = EchoClient( - 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.chat 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.chat] = mock_rpc - request = [{}] - client.chat(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.chat(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_chat_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 = EchoAsyncClient( - 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.chat 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.chat] = mock_rpc - - request = [{}] - await client.chat(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.chat(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoRequest(), - {}, -]) -async def test_chat_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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 - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.chat), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[gs_echo.EchoResponse()]) - response = await client.chat(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, gs_echo.EchoResponse) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandRequest(), - {}, -]) -def test_paged_expand(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - ) - response = client.paged_expand(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.PagedExpandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_paged_expand_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 = EchoClient( - 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 = gs_echo.PagedExpandRequest( - content='content_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.paged_expand), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.paged_expand(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest( - content='content_value', - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_paged_expand_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 = EchoClient( - 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.paged_expand 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.paged_expand] = mock_rpc - request = {} - client.paged_expand(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.paged_expand(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_paged_expand_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 = EchoAsyncClient( - 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.paged_expand 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.paged_expand] = mock_rpc - - request = {} - await client.paged_expand(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.paged_expand(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandRequest(), - {}, -]) -async def test_paged_expand_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.paged_expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - )) - response = await client.paged_expand(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.PagedExpandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_paged_expand_pager(transport_name: str = "grpc"): - client = EchoClient( - 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.paged_expand), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - if HAS_GOOGLE_API_CORE_VERSION_HEADER: - expected_metadata = tuple(expected_metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - pager = client.paged_expand(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gs_echo.EchoResponse) - for i in results) -def test_paged_expand_pages(transport_name: str = "grpc"): - client = EchoClient( - 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.paged_expand), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - pages = list(client.paged_expand(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_paged_expand_async_pager(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - async_pager = await client.paged_expand(request={},) - assert async_pager.next_page_token == 'abc' - assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, gs_echo.EchoResponse) - for i in responses) - - -@pytest.mark.asyncio -async def test_paged_expand_async_pages(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.paged_expand(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", [ - gs_echo.PagedExpandLegacyRequest(), - {}, -]) -def test_paged_expand_legacy(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - ) - response = client.paged_expand_legacy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.PagedExpandLegacyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandLegacyPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_paged_expand_legacy_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 = EchoClient( - 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 = gs_echo.PagedExpandLegacyRequest( - content='content_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.paged_expand_legacy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.paged_expand_legacy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandLegacyRequest( - content='content_value', - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_paged_expand_legacy_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 = EchoClient( - 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.paged_expand_legacy 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.paged_expand_legacy] = mock_rpc - request = {} - client.paged_expand_legacy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.paged_expand_legacy(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_paged_expand_legacy_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 = EchoAsyncClient( - 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.paged_expand_legacy 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.paged_expand_legacy] = mock_rpc - - request = {} - await client.paged_expand_legacy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.paged_expand_legacy(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandLegacyRequest(), - {}, -]) -async def test_paged_expand_legacy_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.paged_expand_legacy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - )) - response = await client.paged_expand_legacy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.PagedExpandLegacyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandLegacyAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_paged_expand_legacy_pager(transport_name: str = "grpc"): - client = EchoClient( - 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.paged_expand_legacy), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - if HAS_GOOGLE_API_CORE_VERSION_HEADER: - expected_metadata = tuple(expected_metadata) + ( - version_header.to_api_version_header("v1_20240408"), - ) - pager = client.paged_expand_legacy(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gs_echo.EchoResponse) - for i in results) -def test_paged_expand_legacy_pages(transport_name: str = "grpc"): - client = EchoClient( - 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.paged_expand_legacy), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - pages = list(client.paged_expand_legacy(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_paged_expand_legacy_async_pager(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - async_pager = await client.paged_expand_legacy(request={},) - assert async_pager.next_page_token == 'abc' - assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, gs_echo.EchoResponse) - for i in responses) - - -@pytest.mark.asyncio -async def test_paged_expand_legacy_async_pages(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.paged_expand_legacy(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", [ - gs_echo.PagedExpandRequest(), - {}, -]) -def test_paged_expand_legacy_mapped(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.PagedExpandLegacyMappedResponse( - next_page_token='next_page_token_value', - ) - response = client.paged_expand_legacy_mapped(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.PagedExpandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandLegacyMappedPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_paged_expand_legacy_mapped_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 = EchoClient( - 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 = gs_echo.PagedExpandRequest( - content='content_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.paged_expand_legacy_mapped), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.paged_expand_legacy_mapped(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest( - content='content_value', - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_paged_expand_legacy_mapped_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 = EchoClient( - 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.paged_expand_legacy_mapped 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.paged_expand_legacy_mapped] = mock_rpc - request = {} - client.paged_expand_legacy_mapped(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.paged_expand_legacy_mapped(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_paged_expand_legacy_mapped_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 = EchoAsyncClient( - 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.paged_expand_legacy_mapped 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.paged_expand_legacy_mapped] = mock_rpc - - request = {} - await client.paged_expand_legacy_mapped(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.paged_expand_legacy_mapped(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandRequest(), - {}, -]) -async def test_paged_expand_legacy_mapped_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.paged_expand_legacy_mapped), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandLegacyMappedResponse( - next_page_token='next_page_token_value', - )) - response = await client.paged_expand_legacy_mapped(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.PagedExpandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandLegacyMappedAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_paged_expand_legacy_mapped_pages(transport_name: str = "grpc"): - client = EchoClient( - 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.paged_expand_legacy_mapped), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'a':gs_echo.PagedExpandResponseList(), - 'b':gs_echo.PagedExpandResponseList(), - 'c':gs_echo.PagedExpandResponseList(), - }, - next_page_token='abc', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={}, - next_page_token='def', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'g':gs_echo.PagedExpandResponseList(), - }, - next_page_token='ghi', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'h':gs_echo.PagedExpandResponseList(), - 'i':gs_echo.PagedExpandResponseList(), - }, - ), - RuntimeError, - ) - pages = list(client.paged_expand_legacy_mapped(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_paged_expand_legacy_mapped_async_pager(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'a':gs_echo.PagedExpandResponseList(), - 'b':gs_echo.PagedExpandResponseList(), - 'c':gs_echo.PagedExpandResponseList(), - }, - next_page_token='abc', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={}, - next_page_token='def', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'g':gs_echo.PagedExpandResponseList(), - }, - next_page_token='ghi', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'h':gs_echo.PagedExpandResponseList(), - 'i':gs_echo.PagedExpandResponseList(), - }, - ), - RuntimeError, - ) - async_pager = await client.paged_expand_legacy_mapped(request={},) - assert async_pager.next_page_token == 'abc' - assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - - assert all( - isinstance(i, tuple) - for i in responses) - for result in responses: - assert isinstance(result, tuple) - assert tuple(type(t) for t in result) == (str, gs_echo.PagedExpandResponseList) - - assert async_pager.get('a') is None - assert isinstance(async_pager.get('h'), gs_echo.PagedExpandResponseList) - - -@pytest.mark.asyncio -async def test_paged_expand_legacy_mapped_async_pages(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'a':gs_echo.PagedExpandResponseList(), - 'b':gs_echo.PagedExpandResponseList(), - 'c':gs_echo.PagedExpandResponseList(), - }, - next_page_token='abc', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={}, - next_page_token='def', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'g':gs_echo.PagedExpandResponseList(), - }, - next_page_token='ghi', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'h':gs_echo.PagedExpandResponseList(), - 'i':gs_echo.PagedExpandResponseList(), - }, - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.paged_expand_legacy_mapped(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", [ - gs_echo.WaitRequest(), - {}, -]) -def test_wait(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.wait), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.wait(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.WaitRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_wait_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 = EchoClient( - 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 = gs_echo.WaitRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.wait), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.wait(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.WaitRequest( - ) - assert args[0] == request_msg - -def test_wait_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 = EchoClient( - 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.wait 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.wait] = mock_rpc - request = {} - client.wait(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.wait(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_wait_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 = EchoAsyncClient( - 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.wait 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.wait] = mock_rpc - - request = {} - await client.wait(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.wait(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.WaitRequest(), - {}, -]) -async def test_wait_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.wait), - '__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.wait(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.WaitRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.BlockRequest(), - {}, -]) -def test_block(request_type, transport: str = 'grpc'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.block), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gs_echo.BlockResponse( - content='content_value', - ) - response = client.block(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gs_echo.BlockRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.BlockResponse) - assert response.content == 'content_value' - - -def test_block_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 = EchoClient( - 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 = gs_echo.BlockRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.block), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.block(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.BlockRequest( - ) - assert args[0] == request_msg - -def test_block_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 = EchoClient( - 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.block 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.block] = mock_rpc - request = {} - client.block(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.block(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_block_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 = EchoAsyncClient( - 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.block 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.block] = mock_rpc - - request = {} - await client.block(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.block(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 -@pytest.mark.parametrize("request_type", [ - gs_echo.BlockRequest(), - {}, -]) -async def test_block_async(request_type, transport: str = 'grpc_asyncio'): - client = EchoAsyncClient( - 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.block), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.BlockResponse( - content='content_value', - )) - response = await client.block(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gs_echo.BlockRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.BlockResponse) - assert response.content == 'content_value' - - -def test_echo_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 = EchoClient( - 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.echo 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.echo] = mock_rpc - - request = {} - client.echo(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.echo(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_echo_error_details_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 = EchoClient( - 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.echo_error_details 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.echo_error_details] = mock_rpc - - request = {} - client.echo_error_details(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.echo_error_details(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_expand_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 = EchoClient( - 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.expand 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.expand] = mock_rpc - - request = {} - client.expand(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.expand(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_expand_rest_flattened(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.EchoResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - content='content_value', - error=status_pb2.Status(code=411), - ) - 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 = gs_echo.EchoResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - client.expand(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/echo:expand" % client.transport._host, args[1]) - - -def test_expand_rest_flattened_error(transport: str = 'rest'): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.expand( - gs_echo.ExpandRequest(), - content='content_value', - error=status_pb2.Status(code=411), - ) - - -def test_collect_rest_unimplemented(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = gs_echo.EchoRequest() - requests = [request] - with pytest.raises(NotImplementedError): - client.collect(requests) - - -def test_chat_rest_no_http_options(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = gs_echo.EchoRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.chat(requests) - - -def test_paged_expand_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 = EchoClient( - 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.paged_expand 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.paged_expand] = mock_rpc - - request = {} - client.paged_expand(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.paged_expand(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_paged_expand_rest_required_fields(request_type=gs_echo.PagedExpandRequest): - transport_class = transports.EchoRestTransport - - request_init = {} - request_init["content"] = "" - 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()).paged_expand._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["content"] = 'content_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).paged_expand._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "content" in jsonified_request - assert jsonified_request["content"] == 'content_value' - - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gs_echo.PagedExpandResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gs_echo.PagedExpandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.paged_expand(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_paged_expand_rest_unset_required_fields(): - transport = transports.EchoRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.paged_expand._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("content", ))) - - -def test_paged_expand_rest_pager(transport: str = 'rest'): - client = EchoClient( - 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 = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(gs_echo.PagedExpandResponse.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 = {} - - pager = client.paged_expand(request=sample_request) - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gs_echo.EchoResponse) - for i in results) - - pages = list(client.paged_expand(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_paged_expand_legacy_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 = EchoClient( - 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.paged_expand_legacy 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.paged_expand_legacy] = mock_rpc - - request = {} - client.paged_expand_legacy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.paged_expand_legacy(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_paged_expand_legacy_rest_required_fields(request_type=gs_echo.PagedExpandLegacyRequest): - transport_class = transports.EchoRestTransport - - request_init = {} - request_init["content"] = "" - 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()).paged_expand_legacy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["content"] = 'content_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).paged_expand_legacy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "content" in jsonified_request - assert jsonified_request["content"] == 'content_value' - - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gs_echo.PagedExpandResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gs_echo.PagedExpandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.paged_expand_legacy(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_paged_expand_legacy_rest_unset_required_fields(): - transport = transports.EchoRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.paged_expand_legacy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("content", ))) - - -def test_paged_expand_legacy_rest_pager(transport: str = 'rest'): - client = EchoClient( - 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 = ( - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - next_page_token='abc', - ), - gs_echo.PagedExpandResponse( - responses=[], - next_page_token='def', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - ], - next_page_token='ghi', - ), - gs_echo.PagedExpandResponse( - responses=[ - gs_echo.EchoResponse(), - gs_echo.EchoResponse(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(gs_echo.PagedExpandResponse.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 = {} - - pager = client.paged_expand_legacy(request=sample_request) - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gs_echo.EchoResponse) - for i in results) - - pages = list(client.paged_expand_legacy(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_paged_expand_legacy_mapped_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 = EchoClient( - 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.paged_expand_legacy_mapped 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.paged_expand_legacy_mapped] = mock_rpc - - request = {} - client.paged_expand_legacy_mapped(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.paged_expand_legacy_mapped(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_paged_expand_legacy_mapped_rest_required_fields(request_type=gs_echo.PagedExpandRequest): - transport_class = transports.EchoRestTransport - - request_init = {} - request_init["content"] = "" - 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()).paged_expand_legacy_mapped._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["content"] = 'content_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).paged_expand_legacy_mapped._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "content" in jsonified_request - assert jsonified_request["content"] == 'content_value' - - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gs_echo.PagedExpandLegacyMappedResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gs_echo.PagedExpandLegacyMappedResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.paged_expand_legacy_mapped(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_paged_expand_legacy_mapped_rest_unset_required_fields(): - transport = transports.EchoRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.paged_expand_legacy_mapped._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("content", ))) - - -def test_paged_expand_legacy_mapped_rest_pager(transport: str = 'rest'): - client = EchoClient( - 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 = ( - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'a':gs_echo.PagedExpandResponseList(), - 'b':gs_echo.PagedExpandResponseList(), - 'c':gs_echo.PagedExpandResponseList(), - }, - next_page_token='abc', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={}, - next_page_token='def', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'g':gs_echo.PagedExpandResponseList(), - }, - next_page_token='ghi', - ), - gs_echo.PagedExpandLegacyMappedResponse( - alphabetized={ - 'h':gs_echo.PagedExpandResponseList(), - 'i':gs_echo.PagedExpandResponseList(), - }, - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(gs_echo.PagedExpandLegacyMappedResponse.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 = {} - - pager = client.paged_expand_legacy_mapped(request=sample_request) - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - assert isinstance(pager.get('a'), gs_echo.PagedExpandResponseList) - assert pager.get('h') is None - - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, tuple) - for i in results) - for result in results: - assert isinstance(result, tuple) - assert tuple(type(t) for t in result) == (str, gs_echo.PagedExpandResponseList) - - assert pager.get('a') is None - assert isinstance(pager.get('h'), gs_echo.PagedExpandResponseList) - - pages = list(client.paged_expand_legacy_mapped(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_wait_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 = EchoClient( - 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.wait 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.wait] = mock_rpc - - request = {} - client.wait(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.wait(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_block_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 = EchoClient( - 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.block 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.block] = mock_rpc - - request = {} - client.block(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.block(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_chat_rest_error(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.chat({}) - assert ( - "Method Chat is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EchoGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EchoGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EchoClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EchoGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EchoClient( - 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 = EchoClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EchoGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EchoClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EchoGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EchoClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EchoGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EchoGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EchoGrpcTransport, - transports.EchoGrpcAsyncIOTransport, - transports.EchoRestTransport, -]) -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 = EchoClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EchoClient( - 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_echo_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_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_echo_error_details_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo_error_details), - '__call__') as call: - call.return_value = gs_echo.EchoErrorDetailsResponse() - client.echo_error_details(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoErrorDetailsRequest() - assert args[0] == request_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_expand_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - call.return_value = iter([gs_echo.EchoResponse()]) - client.expand(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.ExpandRequest() - assert args[0] == request_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_paged_expand_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__') as call: - call.return_value = gs_echo.PagedExpandResponse() - client.paged_expand(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest() - assert args[0] == request_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_paged_expand_legacy_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__') as call: - call.return_value = gs_echo.PagedExpandResponse() - client.paged_expand_legacy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandLegacyRequest() - assert args[0] == request_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_paged_expand_legacy_mapped_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__') as call: - call.return_value = gs_echo.PagedExpandLegacyMappedResponse() - client.paged_expand_legacy_mapped(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest() - assert args[0] == request_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_wait_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.wait), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.wait(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.WaitRequest() - assert args[0] == request_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_block_empty_call_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.block), - '__call__') as call: - call.return_value = gs_echo.BlockResponse() - client.block(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.BlockRequest() - assert args[0] == request_msg - - -def test_echo_routing_parameters_request_1_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_2_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_3_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"header": "regions/sample1/zones/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "regions/sample1/zones/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'regions/sample1/zones/sample2/sample3', 'routing_id': 'regions/sample1/zones/sample2/sample3', 'table_name': 'regions/sample1/zones/sample2/sample3'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_4_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"header": "projects/sample1/sample2"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/sample2"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/sample2', 'routing_id': 'projects/sample1/sample2', 'super_id': 'projects/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_5_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_6_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_7_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"other_header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"other_header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'baz': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_8_grpc(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - call.return_value = gs_echo.EchoResponse() - client.echo(request={"other_header": "projects/sample1/sample2"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"other_header": "projects/sample1/sample2"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'baz': 'projects/sample1/sample2', 'qux': 'projects/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_grpc_asyncio(): - transport = EchoAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EchoAsyncClient( - 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_echo_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_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_echo_error_details_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo_error_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoErrorDetailsResponse( - )) - await client.echo_error_details(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoErrorDetailsRequest() - assert args[0] == request_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_expand_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[gs_echo.EchoResponse()]) - await client.expand(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.ExpandRequest() - assert args[0] == request_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_paged_expand_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - )) - await client.paged_expand(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest() - assert args[0] == request_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_paged_expand_legacy_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - )) - await client.paged_expand_legacy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandLegacyRequest() - assert args[0] == request_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_paged_expand_legacy_mapped_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.PagedExpandLegacyMappedResponse( - next_page_token='next_page_token_value', - )) - await client.paged_expand_legacy_mapped(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest() - assert args[0] == request_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_wait_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.wait), - '__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.wait(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.WaitRequest() - assert args[0] == request_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_block_empty_call_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.block), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.BlockResponse( - content='content_value', - )) - await client.block(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.BlockRequest() - assert args[0] == request_msg - - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_1_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_2_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_3_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"header": "regions/sample1/zones/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "regions/sample1/zones/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'regions/sample1/zones/sample2/sample3', 'routing_id': 'regions/sample1/zones/sample2/sample3', 'table_name': 'regions/sample1/zones/sample2/sample3'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_4_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"header": "projects/sample1/sample2"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/sample2"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/sample2', 'routing_id': 'projects/sample1/sample2', 'super_id': 'projects/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_5_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_6_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_7_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"other_header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"other_header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'baz': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_echo_routing_parameters_request_8_grpc_asyncio(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_value', - )) - await client.echo(request={"other_header": "projects/sample1/sample2"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"other_header": "projects/sample1/sample2"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'baz': 'projects/sample1/sample2', 'qux': 'projects/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_rest(): - transport = EchoClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_echo_rest_bad_request(request_type=gs_echo.EchoRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.echo(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoRequest, - dict, -]) -def test_echo_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_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 = gs_echo.EchoResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.echo(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoResponse) - assert response.content == 'content_value' - assert response.severity == gs_echo.Severity.NECESSARY - assert response.request_id == 'request_id_value' - assert response.other_request_id == 'other_request_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_echo_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_echo") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_echo_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_echo") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.EchoRequest.pb(gs_echo.EchoRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.EchoResponse.to_json(gs_echo.EchoResponse()) - req.return_value.content = return_value - - request = gs_echo.EchoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.EchoResponse() - post_with_metadata.return_value = gs_echo.EchoResponse(), metadata - - client.echo(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_echo_error_details_rest_bad_request(request_type=gs_echo.EchoErrorDetailsRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.echo_error_details(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.EchoErrorDetailsRequest, - dict, -]) -def test_echo_error_details_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.EchoErrorDetailsResponse( - ) - - # 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 = gs_echo.EchoErrorDetailsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.echo_error_details(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoErrorDetailsResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_echo_error_details_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_echo_error_details") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_echo_error_details_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_echo_error_details") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.EchoErrorDetailsRequest.pb(gs_echo.EchoErrorDetailsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.EchoErrorDetailsResponse.to_json(gs_echo.EchoErrorDetailsResponse()) - req.return_value.content = return_value - - request = gs_echo.EchoErrorDetailsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.EchoErrorDetailsResponse() - post_with_metadata.return_value = gs_echo.EchoErrorDetailsResponse(), metadata - - client.echo_error_details(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_expand_rest_bad_request(request_type=gs_echo.ExpandRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.expand(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.ExpandRequest, - dict, -]) -def test_expand_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.EchoResponse( - content='content_value', - severity=gs_echo.Severity.NECESSARY, - request_id='request_id_value', - other_request_id='other_request_id_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 = gs_echo.EchoResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.expand(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.EchoResponse) - assert response.content == 'content_value' - assert response.severity == gs_echo.Severity.NECESSARY - assert response.request_id == 'request_id_value' - assert response.other_request_id == 'other_request_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_expand_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_expand") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_expand_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_expand") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.ExpandRequest.pb(gs_echo.ExpandRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.EchoResponse.to_json(gs_echo.EchoResponse()) - req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) - - request = gs_echo.ExpandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.EchoResponse() - post_with_metadata.return_value = gs_echo.EchoResponse(), metadata - - client.expand(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_collect_rest_error(): - - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.collect({}) - assert ( - "Method Collect is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_chat_rest_error(): - - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.chat({}) - assert ( - "Method Chat is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_paged_expand_rest_bad_request(request_type=gs_echo.PagedExpandRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.paged_expand(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandRequest, - dict, -]) -def test_paged_expand_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gs_echo.PagedExpandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.paged_expand(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_paged_expand_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_paged_expand") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_paged_expand_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_paged_expand") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.PagedExpandRequest.pb(gs_echo.PagedExpandRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.PagedExpandResponse.to_json(gs_echo.PagedExpandResponse()) - req.return_value.content = return_value - - request = gs_echo.PagedExpandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.PagedExpandResponse() - post_with_metadata.return_value = gs_echo.PagedExpandResponse(), metadata - - client.paged_expand(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_paged_expand_legacy_rest_bad_request(request_type=gs_echo.PagedExpandLegacyRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.paged_expand_legacy(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandLegacyRequest, - dict, -]) -def test_paged_expand_legacy_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.PagedExpandResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gs_echo.PagedExpandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.paged_expand_legacy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandLegacyPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_paged_expand_legacy_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_paged_expand_legacy") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_paged_expand_legacy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_paged_expand_legacy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.PagedExpandLegacyRequest.pb(gs_echo.PagedExpandLegacyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.PagedExpandResponse.to_json(gs_echo.PagedExpandResponse()) - req.return_value.content = return_value - - request = gs_echo.PagedExpandLegacyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.PagedExpandResponse() - post_with_metadata.return_value = gs_echo.PagedExpandResponse(), metadata - - client.paged_expand_legacy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_paged_expand_legacy_mapped_rest_bad_request(request_type=gs_echo.PagedExpandRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.paged_expand_legacy_mapped(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.PagedExpandRequest, - dict, -]) -def test_paged_expand_legacy_mapped_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.PagedExpandLegacyMappedResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gs_echo.PagedExpandLegacyMappedResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.paged_expand_legacy_mapped(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PagedExpandLegacyMappedPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_paged_expand_legacy_mapped_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_paged_expand_legacy_mapped") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_paged_expand_legacy_mapped_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_paged_expand_legacy_mapped") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.PagedExpandRequest.pb(gs_echo.PagedExpandRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.PagedExpandLegacyMappedResponse.to_json(gs_echo.PagedExpandLegacyMappedResponse()) - req.return_value.content = return_value - - request = gs_echo.PagedExpandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.PagedExpandLegacyMappedResponse() - post_with_metadata.return_value = gs_echo.PagedExpandLegacyMappedResponse(), metadata - - client.paged_expand_legacy_mapped(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_wait_rest_bad_request(request_type=gs_echo.WaitRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.wait(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.WaitRequest, - dict, -]) -def test_wait_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.wait(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_wait_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_wait") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_wait_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_wait") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.WaitRequest.pb(gs_echo.WaitRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gs_echo.WaitRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.wait(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_block_rest_bad_request(request_type=gs_echo.BlockRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.block(request) - - -@pytest.mark.parametrize("request_type", [ - gs_echo.BlockRequest, - dict, -]) -def test_block_rest_call_success(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gs_echo.BlockResponse( - content='content_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 = gs_echo.BlockResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.block(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gs_echo.BlockResponse) - assert response.content == 'content_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_block_rest_interceptors(null_interceptor): - transport = transports.EchoRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EchoRestInterceptor(), - ) - client = EchoClient(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.EchoRestInterceptor, "post_block") as post, \ - mock.patch.object(transports.EchoRestInterceptor, "post_block_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EchoRestInterceptor, "pre_block") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gs_echo.BlockRequest.pb(gs_echo.BlockRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gs_echo.BlockResponse.to_json(gs_echo.BlockResponse()) - req.return_value.content = return_value - - request = gs_echo.BlockRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gs_echo.BlockResponse() - post_with_metadata.return_value = gs_echo.BlockResponse(), metadata - - client.block(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_initialize_client_w_rest(): - client = EchoClient( - 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_echo_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_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_echo_error_details_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo_error_details), - '__call__') as call: - client.echo_error_details(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.EchoErrorDetailsRequest() - assert args[0] == request_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_expand_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.expand), - '__call__') as call: - client.expand(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.ExpandRequest() - assert args[0] == request_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_paged_expand_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand), - '__call__') as call: - client.paged_expand(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest() - assert args[0] == request_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_paged_expand_legacy_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy), - '__call__') as call: - client.paged_expand_legacy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandLegacyRequest() - assert args[0] == request_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_paged_expand_legacy_mapped_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.paged_expand_legacy_mapped), - '__call__') as call: - client.paged_expand_legacy_mapped(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.PagedExpandRequest() - assert args[0] == request_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_wait_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.wait), - '__call__') as call: - client.wait(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.WaitRequest() - assert args[0] == request_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_block_empty_call_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.block), - '__call__') as call: - client.block(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gs_echo.BlockRequest() - assert args[0] == request_msg - - -def test_echo_routing_parameters_request_1_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_2_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'sample1', 'routing_id': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_3_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"header": "regions/sample1/zones/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "regions/sample1/zones/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'regions/sample1/zones/sample2/sample3', 'routing_id': 'regions/sample1/zones/sample2/sample3', 'table_name': 'regions/sample1/zones/sample2/sample3'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_4_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"header": "projects/sample1/sample2"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/sample2"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/sample2', 'routing_id': 'projects/sample1/sample2', 'super_id': 'projects/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_5_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_6_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"header": "projects/sample1/instances/sample2/sample3"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"header": "projects/sample1/instances/sample2/sample3"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'header': 'projects/sample1/instances/sample2/sample3', 'routing_id': 'projects/sample1/instances/sample2/sample3', 'super_id': 'projects/sample1', 'table_name': 'projects/sample1/instances/sample2/sample3', 'instance_id': 'instances/sample2'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_7_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"other_header": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"other_header": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'baz': 'sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_echo_routing_parameters_request_8_rest(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.echo), - '__call__') as call: - client.echo(request={"other_header": "projects/sample1/sample2"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = gs_echo.EchoRequest(**{"other_header": "projects/sample1/sample2"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].other_request_id) - request_msg.other_request_id = args[0].other_request_id - assert args[0] == request_msg - - expected_headers = {'baz': 'projects/sample1/sample2', 'qux': 'projects/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_echo_rest_lro_client(): - client = EchoClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EchoGrpcTransport, - ) - -def test_echo_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EchoTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_echo_base_transport(): - # Instantiate the base transport. - with mock.patch('google.showcase_v1beta1.services.echo.transports.EchoTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EchoTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'echo', - 'echo_error_details', - 'expand', - 'collect', - 'chat', - 'paged_expand', - 'paged_expand_legacy', - 'paged_expand_legacy_mapped', - 'wait', - 'block', - '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_echo_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.showcase_v1beta1.services.echo.transports.EchoTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EchoTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_echo_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.showcase_v1beta1.services.echo.transports.EchoTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EchoTransport() - adc.assert_called_once() - - -def test_echo_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) - EchoClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EchoGrpcTransport, - transports.EchoGrpcAsyncIOTransport, - ], -) -def test_echo_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EchoGrpcTransport, - transports.EchoGrpcAsyncIOTransport, - transports.EchoRestTransport, - ], -) -def test_echo_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.EchoGrpcTransport, grpc_helpers), - (transports.EchoGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_echo_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( - "localhost:7469", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="localhost:7469", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EchoGrpcTransport, transports.EchoGrpcAsyncIOTransport]) -def test_echo_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_echo_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.EchoRestTransport ( - 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_echo_host_no_port(transport_name): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='localhost'), - transport=transport_name, - ) - assert client.transport._host == ( - 'localhost:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://localhost' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_echo_host_with_port(transport_name): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='localhost:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'localhost:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://localhost:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_echo_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EchoClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EchoClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.echo._session - session2 = client2.transport.echo._session - assert session1 != session2 - session1 = client1.transport.echo_error_details._session - session2 = client2.transport.echo_error_details._session - assert session1 != session2 - session1 = client1.transport.expand._session - session2 = client2.transport.expand._session - assert session1 != session2 - session1 = client1.transport.collect._session - session2 = client2.transport.collect._session - assert session1 != session2 - session1 = client1.transport.chat._session - session2 = client2.transport.chat._session - assert session1 != session2 - session1 = client1.transport.paged_expand._session - session2 = client2.transport.paged_expand._session - assert session1 != session2 - session1 = client1.transport.paged_expand_legacy._session - session2 = client2.transport.paged_expand_legacy._session - assert session1 != session2 - session1 = client1.transport.paged_expand_legacy_mapped._session - session2 = client2.transport.paged_expand_legacy_mapped._session - assert session1 != session2 - session1 = client1.transport.wait._session - session2 = client2.transport.wait._session - assert session1 != session2 - session1 = client1.transport.block._session - session2 = client2.transport.block._session - assert session1 != session2 -def test_echo_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EchoGrpcTransport( - 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_echo_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EchoGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize("transport_class", [transports.EchoGrpcTransport, transports.EchoGrpcAsyncIOTransport]) -def test_echo_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.EchoGrpcTransport, transports.EchoGrpcAsyncIOTransport]) -def test_echo_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_echo_grpc_lro_client(): - client = EchoClient( - 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_echo_grpc_lro_async_client(): - client = EchoAsyncClient( - 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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EchoClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = EchoClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EchoClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = EchoClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = EchoClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EchoClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EchoClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = EchoClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EchoClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = EchoClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = EchoClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EchoClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = EchoClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = EchoClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EchoClient.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.EchoTransport, '_prep_wrapped_messages') as prep: - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EchoTransport, '_prep_wrapped_messages') as prep: - transport_class = EchoClient.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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_delete_operation_flattened(): - client = EchoClient( - 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 - - client.delete_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() - -@pytest.mark.asyncio -async def test_delete_operation_flattened_async(): - client = EchoAsyncClient( - 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 - ) - await client.delete_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() - - -def test_cancel_operation(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_cancel_operation_flattened(): - client = EchoClient( - 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 - - client.cancel_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() - -@pytest.mark.asyncio -async def test_cancel_operation_flattened_async(): - client = EchoAsyncClient( - 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 - ) - await client.cancel_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() - - -def test_get_operation(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_get_operation_flattened(): - client = EchoClient( - 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() - - client.get_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() - -@pytest.mark.asyncio -async def test_get_operation_flattened_async(): - client = EchoAsyncClient( - 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() - ) - await client.get_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() - - -def test_list_operations(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_operations_flattened(): - client = EchoClient( - 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() - - client.list_operations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() - -@pytest.mark.asyncio -async def test_list_operations_flattened_async(): - client = EchoAsyncClient( - 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() - ) - await client.list_operations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() - - -def test_list_locations(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_list_locations_flattened(): - client = EchoClient( - 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() - - client.list_locations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() - -@pytest.mark.asyncio -async def test_list_locations_flattened_async(): - client = EchoAsyncClient( - 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() - ) - await client.list_locations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() - - -def test_get_location(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_get_location_flattened(): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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() - - client.get_location() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() - -@pytest.mark.asyncio -async def test_get_location_flattened_async(): - client = EchoAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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() - ) - await client.get_location() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() - - -def test_set_iam_policy(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_set_iam_policy_flattened(): - client = EchoClient( - 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() - - client.set_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = EchoAsyncClient( - 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() - ) - - await client.set_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -def test_get_iam_policy(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_get_iam_policy_flattened(): - client = EchoClient( - 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() - - client.get_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = EchoAsyncClient( - 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() - ) - - await client.get_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -def test_test_iam_permissions(transport: str = "grpc"): - client = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EchoAsyncClient( - 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 = EchoClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoAsyncClient( - 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_test_iam_permissions_flattened(): - client = EchoClient( - 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() - - client.test_iam_permissions() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = EchoAsyncClient( - 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() - ) - - await client.test_iam_permissions() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_transport_close_grpc(): - client = EchoClient( - 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 = EchoAsyncClient( - 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 = EchoClient( - 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 = EchoClient( - 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", [ - (EchoClient, transports.EchoGrpcTransport), - (EchoAsyncClient, transports.EchoGrpcAsyncIOTransport), -]) -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/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py deleted file mode 100644 index 7e61c0e1393d..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py +++ /dev/null @@ -1,6950 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 asyncio -import re -from unittest import mock -from unittest.mock import AsyncMock - -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 collections.abc import Sequence, Mapping -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 gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.showcase_v1beta1.services.identity import IdentityAsyncClient -from google.showcase_v1beta1.services.identity import IdentityClient -from google.showcase_v1beta1.services.identity import pagers -from google.showcase_v1beta1.services.identity import transports -from google.showcase_v1beta1.types import identity -import google.auth -import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) -_UUID4_RE = re.compile(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}") - - -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 - - -@pytest.fixture(autouse=True) -def set_event_loop(): - try: - asyncio.get_running_loop() - yield - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - yield - finally: - loop.close() - asyncio.set_event_loop(None) - - -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" - custom_endpoint = ".custom" - - assert IdentityClient._get_default_mtls_endpoint(None) is None - assert IdentityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert IdentityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert IdentityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert IdentityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert IdentityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - assert IdentityClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint - -def test__read_environment_variables(): - assert IdentityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert IdentityClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert IdentityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with pytest.raises(ValueError) as excinfo: - IdentityClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - else: - assert IdentityClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert IdentityClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert IdentityClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert IdentityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - IdentityClient._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 IdentityClient._read_environment_variables() == (False, "auto", "foo.com") - - -def test_use_client_cert_effective(): - # Test case 1: Test when `should_use_client_cert` returns True. - # We mock the `should_use_client_cert` function to simulate a scenario where - # the google-auth library supports automatic mTLS and determines that a - # client certificate should be used. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): - assert IdentityClient._use_client_cert_effective() is True - - # Test case 2: Test when `should_use_client_cert` returns False. - # We mock the `should_use_client_cert` function to simulate a scenario where - # the google-auth library supports automatic mTLS and determines that a - # client certificate should NOT be used. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): - assert IdentityClient._use_client_cert_effective() is False - - # Test case 3: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert IdentityClient._use_client_cert_effective() is True - - # Test case 4: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert IdentityClient._use_client_cert_effective() is False - - # Test case 5: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): - assert IdentityClient._use_client_cert_effective() is True - - # Test case 6: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): - assert IdentityClient._use_client_cert_effective() is False - - # Test case 7: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): - assert IdentityClient._use_client_cert_effective() is True - - # Test case 8: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): - assert IdentityClient._use_client_cert_effective() is False - - # Test case 9: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. - # In this case, the method should return False, which is the default value. - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, clear=True): - assert IdentityClient._use_client_cert_effective() is False - - # Test case 10: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. - # The method should raise a ValueError as the environment variable must be either - # "true" or "false". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): - with pytest.raises(ValueError): - IdentityClient._use_client_cert_effective() - - # Test case 11: Test when `should_use_client_cert` is available and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. - # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): - assert IdentityClient._use_client_cert_effective() is False - - # Test case 12: Test when `should_use_client_cert` is available and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, - # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): - with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): - assert IdentityClient._use_client_cert_effective() is False - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert IdentityClient._get_client_cert_source(None, False) is None - assert IdentityClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert IdentityClient._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 IdentityClient._get_client_cert_source(None, True) is mock_default_cert_source - assert IdentityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) -@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = IdentityClient._DEFAULT_UNIVERSE - default_endpoint = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert IdentityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert IdentityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == IdentityClient.DEFAULT_MTLS_ENDPOINT - assert IdentityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert IdentityClient._get_api_endpoint(None, None, default_universe, "always") == IdentityClient.DEFAULT_MTLS_ENDPOINT - assert IdentityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == IdentityClient.DEFAULT_MTLS_ENDPOINT - assert IdentityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert IdentityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - IdentityClient._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 IdentityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert IdentityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert IdentityClient._get_universe_domain(None, None) == IdentityClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - IdentityClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = IdentityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = IdentityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -def test__setup_request_id(): - class MockRequest: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - def __contains__(self, key): - return hasattr(self, key) - - class MockProtoRequest: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - def HasField(self, key): - return hasattr(self, key) - - # Test with proto3 optional field not in request - request = MockRequest() - IdentityClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with proto3 optional field already in request - request = MockRequest(request_id="already_set") - IdentityClient._setup_request_id(request, "request_id", True) - assert request.request_id == "already_set" - - # Test with non-proto3 optional field empty - request = MockRequest(request_id="") - IdentityClient._setup_request_id(request, "request_id", False) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with non-proto3 optional field already set - request = MockRequest(request_id="already_set") - IdentityClient._setup_request_id(request, "request_id", False) - assert request.request_id == "already_set" - - # Test with proto3 optional field not in request (MockProtoRequest) - request = MockProtoRequest() - IdentityClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with proto3 optional field already in request (MockProtoRequest) - request = MockProtoRequest(request_id="already_set") - IdentityClient._setup_request_id(request, "request_id", True) - assert request.request_id == "already_set" - - # Test with ValueError - class MockValueErrorRequest: - def HasField(self, key): - raise ValueError("Mismatched field") - def __contains__(self, key): - return hasattr(self, key) - - request = MockValueErrorRequest() - IdentityClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with dict and proto3 optional field not in request - request = {} - IdentityClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) - - # Test with dict and proto3 optional field already in request - request = {"request_id": "already_set"} - IdentityClient._setup_request_id(request, "request_id", True) - assert request["request_id"] == "already_set" - - # Test with dict and non-proto3 optional field empty - request = {"request_id": ""} - IdentityClient._setup_request_id(request, "request_id", False) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) - - # Test with dict and non-proto3 optional field already set - request = {"request_id": "already_set"} - IdentityClient._setup_request_id(request, "request_id", False) - assert request["request_id"] == "already_set" - -@pytest.mark.parametrize("client_class,transport_name", [ - (IdentityClient, "grpc"), - (IdentityAsyncClient, "grpc_asyncio"), - (IdentityClient, "rest"), -]) -def test_identity_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 == ( - 'localhost:7469' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://localhost:7469' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.IdentityGrpcTransport, "grpc"), - (transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.IdentityRestTransport, "rest"), -]) -def test_identity_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", [ - (IdentityClient, "grpc"), - (IdentityAsyncClient, "grpc_asyncio"), - (IdentityClient, "rest"), -]) -def test_identity_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 == ( - 'localhost:7469' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://localhost:7469' - ) - - -def test_identity_client_get_transport_class(): - transport = IdentityClient.get_transport_class() - available_transports = [ - transports.IdentityGrpcTransport, - transports.IdentityRestTransport, - ] - assert transport in available_transports - - transport = IdentityClient.get_transport_class("grpc") - assert transport == transports.IdentityGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IdentityClient, transports.IdentityGrpcTransport, "grpc"), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio"), - (IdentityClient, transports.IdentityRestTransport, "rest"), -]) -@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) -@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) -def test_identity_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(IdentityClient, '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(IdentityClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (IdentityClient, transports.IdentityGrpcTransport, "grpc", "true"), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (IdentityClient, transports.IdentityGrpcTransport, "grpc", "false"), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (IdentityClient, transports.IdentityRestTransport, "rest", "true"), - (IdentityClient, transports.IdentityRestTransport, "rest", "false"), -]) -@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) -@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_identity_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", [ - IdentityClient, IdentityAsyncClient -]) -@mock.patch.object(IdentityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IdentityClient)) -@mock.patch.object(IdentityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IdentityAsyncClient)) -def test_identity_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. - test_cases = [ - ( - # With workloads present in config, mTLS is enabled. - { - "version": 1, - "cert_configs": { - "workload": { - "cert_path": "path/to/cert/file", - "key_path": "path/to/key/file", - } - }, - }, - mock_client_cert_source, - ), - ( - # With workloads not present in config, mTLS is disabled. - { - "version": 1, - "cert_configs": {}, - }, - None, - ), - ] - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - for config_data, expected_cert_source in test_cases: - env = os.environ.copy() - env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) - with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source - - # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). - test_cases = [ - ( - # With workloads present in config, mTLS is enabled. - { - "version": 1, - "cert_configs": { - "workload": { - "cert_path": "path/to/cert/file", - "key_path": "path/to/key/file", - } - }, - }, - mock_client_cert_source, - ), - ( - # With workloads not present in config, mTLS is disabled. - { - "version": 1, - "cert_configs": {}, - }, - None, - ), - ] - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - for config_data, expected_cert_source in test_cases: - env = os.environ.copy() - env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") - with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - -@pytest.mark.parametrize("client_class", [ - IdentityClient, IdentityAsyncClient -]) -@mock.patch.object(IdentityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityClient)) -@mock.patch.object(IdentityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IdentityAsyncClient)) -def test_identity_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = IdentityClient._DEFAULT_UNIVERSE - default_endpoint = IdentityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = IdentityClient._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", [ - (IdentityClient, transports.IdentityGrpcTransport, "grpc"), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio"), - (IdentityClient, transports.IdentityRestTransport, "rest"), -]) -def test_identity_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", [ - (IdentityClient, transports.IdentityGrpcTransport, "grpc", grpc_helpers), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (IdentityClient, transports.IdentityRestTransport, "rest", None), -]) -def test_identity_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_identity_client_client_options_from_dict(): - with mock.patch('google.showcase_v1beta1.services.identity.transports.IdentityGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = IdentityClient( - 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", [ - (IdentityClient, transports.IdentityGrpcTransport, "grpc", grpc_helpers), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_identity_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( - "localhost:7469", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="localhost:7469", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - identity.CreateUserRequest(), - {}, -]) -def test_create_user(request_type, transport: str = 'grpc'): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - ) - response = client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = identity.CreateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -def test_create_user_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 = IdentityClient( - 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 = identity.CreateUserRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.CreateUserRequest( - ) - assert args[0] == request_msg - -def test_create_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - request = {} - client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user(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_user_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 = IdentityAsyncClient( - 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_user 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_user] = mock_rpc - - request = {} - await client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_user(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 -@pytest.mark.parametrize("request_type", [ - identity.CreateUserRequest(), - {}, -]) -async def test_create_user_async(request_type, transport: str = 'grpc_asyncio'): - client = IdentityAsyncClient( - 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_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - )) - response = await client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = identity.CreateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -def test_create_user_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_user( - display_name='display_name_value', - email='email_value', - age=301, - nickname='nickname_value', - enable_notifications=True, - height_feet=0.1148, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].user.display_name - mock_val = 'display_name_value' - assert arg == mock_val - arg = args[0].user.email - mock_val = 'email_value' - assert arg == mock_val - arg = args[0].user.age - mock_val = 301 - assert arg == mock_val - arg = args[0].user.nickname - mock_val = 'nickname_value' - assert arg == mock_val - arg = args[0].user.enable_notifications - mock_val = True - assert arg == mock_val - arg = args[0].user.height_feet - mock_val = 0.1148 - assert arg == mock_val - - -def test_create_user_flattened_error(): - client = IdentityClient( - credentials=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_user( - identity.CreateUserRequest(), - display_name='display_name_value', - email='email_value', - age=301, - nickname='nickname_value', - enable_notifications=True, - height_feet=0.1148, - ) - -@pytest.mark.asyncio -async def test_create_user_flattened_async(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_user( - display_name='display_name_value', - email='email_value', - age=301, - nickname='nickname_value', - enable_notifications=True, - height_feet=0.1148, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].user.display_name - mock_val = 'display_name_value' - assert arg == mock_val - arg = args[0].user.email - mock_val = 'email_value' - assert arg == mock_val - arg = args[0].user.age - mock_val = 301 - assert arg == mock_val - arg = args[0].user.nickname - mock_val = 'nickname_value' - assert arg == mock_val - arg = args[0].user.enable_notifications - mock_val = True - assert arg == mock_val - arg = args[0].user.height_feet - mock_val = 0.1148 - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_user_flattened_error_async(): - client = IdentityAsyncClient( - 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_user( - identity.CreateUserRequest(), - display_name='display_name_value', - email='email_value', - age=301, - nickname='nickname_value', - enable_notifications=True, - height_feet=0.1148, - ) - - -@pytest.mark.parametrize("request_type", [ - identity.GetUserRequest(), - {}, -]) -def test_get_user(request_type, transport: str = 'grpc'): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - ) - response = client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = identity.GetUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -def test_get_user_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 = IdentityClient( - 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 = identity.GetUserRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.GetUserRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_get_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - request = {} - client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user(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_user_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 = IdentityAsyncClient( - 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_user 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_user] = mock_rpc - - request = {} - await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_user(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 -@pytest.mark.parametrize("request_type", [ - identity.GetUserRequest(), - {}, -]) -async def test_get_user_async(request_type, transport: str = 'grpc_asyncio'): - client = IdentityAsyncClient( - 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_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - )) - response = await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = identity.GetUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - -def test_get_user_field_headers(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = identity.GetUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value = identity.User() - client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_user_field_headers_async(): - client = IdentityAsyncClient( - 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 = identity.GetUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) - await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_user_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_user( - name='name_value', - ) - - # Establish that the 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_user_flattened_error(): - client = IdentityClient( - credentials=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_user( - identity.GetUserRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_user_flattened_async(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_user( - name='name_value', - ) - - # Establish that 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_user_flattened_error_async(): - client = IdentityAsyncClient( - 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_user( - identity.GetUserRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - identity.UpdateUserRequest(), - {}, -]) -def test_update_user(request_type, transport: str = 'grpc'): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - ) - response = client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = identity.UpdateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -def test_update_user_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 = IdentityClient( - 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 = identity.UpdateUserRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.UpdateUserRequest( - ) - assert args[0] == request_msg - -def test_update_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - request = {} - client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user(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_user_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 = IdentityAsyncClient( - 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_user 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_user] = mock_rpc - - request = {} - await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_user(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 -@pytest.mark.parametrize("request_type", [ - identity.UpdateUserRequest(), - {}, -]) -async def test_update_user_async(request_type, transport: str = 'grpc_asyncio'): - client = IdentityAsyncClient( - 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_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - )) - response = await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = identity.UpdateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - -def test_update_user_field_headers(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = identity.UpdateUserRequest() - - request.user.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value = identity.User() - client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'user.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_user_field_headers_async(): - client = IdentityAsyncClient( - 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 = identity.UpdateUserRequest() - - request.user.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User()) - await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'user.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - identity.DeleteUserRequest(), - {}, -]) -def test_delete_user(request_type, transport: str = 'grpc'): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = identity.DeleteUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_user_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 = IdentityClient( - 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 = identity.DeleteUserRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.DeleteUserRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_delete_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - request = {} - client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user(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_user_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 = IdentityAsyncClient( - 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_user 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_user] = mock_rpc - - request = {} - await client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_user(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 -@pytest.mark.parametrize("request_type", [ - identity.DeleteUserRequest(), - {}, -]) -async def test_delete_user_async(request_type, transport: str = 'grpc_asyncio'): - client = IdentityAsyncClient( - 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_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = identity.DeleteUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_user_field_headers(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = identity.DeleteUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value = None - client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_user_field_headers_async(): - client = IdentityAsyncClient( - 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 = identity.DeleteUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_user_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_user( - name='name_value', - ) - - # Establish that the 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_user_flattened_error(): - client = IdentityClient( - credentials=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_user( - identity.DeleteUserRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_user_flattened_async(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_user( - name='name_value', - ) - - # Establish that 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_user_flattened_error_async(): - client = IdentityAsyncClient( - 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_user( - identity.DeleteUserRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - identity.ListUsersRequest(), - {}, -]) -def test_list_users(request_type, transport: str = 'grpc'): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = identity.ListUsersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = identity.ListUsersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_users_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 = IdentityClient( - 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 = identity.ListUsersRequest( - 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_users), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_users(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.ListUsersRequest( - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_list_users_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 = IdentityClient( - 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_users 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_users] = mock_rpc - request = {} - client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_users(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_users_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 = IdentityAsyncClient( - 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_users 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_users] = mock_rpc - - request = {} - await client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_users(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 -@pytest.mark.parametrize("request_type", [ - identity.ListUsersRequest(), - {}, -]) -async def test_list_users_async(request_type, transport: str = 'grpc_asyncio'): - client = IdentityAsyncClient( - 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_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(identity.ListUsersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = identity.ListUsersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_users_pager(transport_name: str = "grpc"): - client = IdentityClient( - 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_users), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - identity.User(), - ], - next_page_token='abc', - ), - identity.ListUsersResponse( - users=[], - next_page_token='def', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - ], - next_page_token='ghi', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_users(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, identity.User) - for i in results) -def test_list_users_pages(transport_name: str = "grpc"): - client = IdentityClient( - 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_users), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - identity.User(), - ], - next_page_token='abc', - ), - identity.ListUsersResponse( - users=[], - next_page_token='def', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - ], - next_page_token='ghi', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - ], - ), - RuntimeError, - ) - pages = list(client.list_users(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_users_async_pager(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - identity.User(), - ], - next_page_token='abc', - ), - identity.ListUsersResponse( - users=[], - next_page_token='def', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - ], - next_page_token='ghi', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_users(request={},) - assert async_pager.next_page_token == 'abc' - assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, identity.User) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_users_async_pages(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - identity.User(), - ], - next_page_token='abc', - ), - identity.ListUsersResponse( - users=[], - next_page_token='def', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - ], - next_page_token='ghi', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.list_users(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - - request = {} - client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user(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_user_rest_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = identity.User() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - display_name='display_name_value', - email='email_value', - age=301, - nickname='nickname_value', - enable_notifications=True, - height_feet=0.1148, - ) - 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 = identity.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_user(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/users" % client.transport._host, args[1]) - - -def test_create_user_rest_flattened_error(transport: str = 'rest'): - client = IdentityClient( - credentials=ga_credentials.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_user( - identity.CreateUserRequest(), - display_name='display_name_value', - email='email_value', - age=301, - nickname='nickname_value', - enable_notifications=True, - height_feet=0.1148, - ) - - -def test_get_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - - request = {} - client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user(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_user_rest_required_fields(request_type=identity.GetUserRequest): - transport_class = transports.IdentityRestTransport - - 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_user._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_user._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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = identity.User() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = identity.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_user(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_get_user_rest_unset_required_fields(): - transport = transports.IdentityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_user_rest_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = identity.User() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'users/sample1'} - - # 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 = identity.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_user(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=users/*}" % client.transport._host, args[1]) - - -def test_get_user_rest_flattened_error(transport: str = 'rest'): - client = IdentityClient( - credentials=ga_credentials.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_user( - identity.GetUserRequest(), - name='name_value', - ) - - -def test_update_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - - request = {} - client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user(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_user_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 = IdentityClient( - 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_user 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_user] = mock_rpc - - request = {} - client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user(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_user_rest_required_fields(request_type=identity.DeleteUserRequest): - transport_class = transports.IdentityRestTransport - - 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_user._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_user._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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_user(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_delete_user_rest_unset_required_fields(): - transport = transports.IdentityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_user_rest_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'users/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_user(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=users/*}" % client.transport._host, args[1]) - - -def test_delete_user_rest_flattened_error(transport: str = 'rest'): - client = IdentityClient( - credentials=ga_credentials.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_user( - identity.DeleteUserRequest(), - name='name_value', - ) - - -def test_list_users_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 = IdentityClient( - 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_users 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_users] = mock_rpc - - request = {} - client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_users(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_users_rest_pager(transport: str = 'rest'): - client = IdentityClient( - 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 = ( - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - identity.User(), - ], - next_page_token='abc', - ), - identity.ListUsersResponse( - users=[], - next_page_token='def', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - ], - next_page_token='ghi', - ), - identity.ListUsersResponse( - users=[ - identity.User(), - identity.User(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(identity.ListUsersResponse.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 = {} - - pager = client.list_users(request=sample_request) - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, identity.User) - for i in results) - - pages = list(client.list_users(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.IdentityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.IdentityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IdentityClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.IdentityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = IdentityClient( - 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 = IdentityClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.IdentityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IdentityClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.IdentityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = IdentityClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.IdentityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.IdentityGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.IdentityGrpcTransport, - transports.IdentityGrpcAsyncIOTransport, - transports.IdentityRestTransport, -]) -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 = IdentityClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_user_empty_call_grpc(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value = identity.User() - client.create_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.CreateUserRequest() - assert args[0] == request_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_user_empty_call_grpc(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value = identity.User() - client.get_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.GetUserRequest() - assert args[0] == request_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_user_empty_call_grpc(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value = identity.User() - client.update_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.UpdateUserRequest() - assert args[0] == request_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_user_empty_call_grpc(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value = None - client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.DeleteUserRequest() - assert args[0] == request_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_users_empty_call_grpc(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - call.return_value = identity.ListUsersResponse() - client.list_users(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.ListUsersRequest() - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = IdentityAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_user_empty_call_grpc_asyncio(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - )) - await client.create_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.CreateUserRequest() - assert args[0] == request_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_user_empty_call_grpc_asyncio(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - )) - await client.get_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.GetUserRequest() - assert args[0] == request_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_user_empty_call_grpc_asyncio(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - )) - await client.update_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.UpdateUserRequest() - assert args[0] == request_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_user_empty_call_grpc_asyncio(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.DeleteUserRequest() - assert args[0] == request_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_users_empty_call_grpc_asyncio(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(identity.ListUsersResponse( - next_page_token='next_page_token_value', - )) - await client.list_users(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.ListUsersRequest() - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = IdentityClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_user_rest_bad_request(request_type=identity.CreateUserRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_user(request) - - -@pytest.mark.parametrize("request_type", [ - identity.CreateUserRequest, - dict, -]) -def test_create_user_rest_call_success(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - ) - - # 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 = identity.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_user(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_rest_interceptors(null_interceptor): - transport = transports.IdentityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), - ) - client = IdentityClient(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.IdentityRestInterceptor, "post_create_user") as post, \ - mock.patch.object(transports.IdentityRestInterceptor, "post_create_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IdentityRestInterceptor, "pre_create_user") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = identity.CreateUserRequest.pb(identity.CreateUserRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = identity.User.to_json(identity.User()) - req.return_value.content = return_value - - request = identity.CreateUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = identity.User() - post_with_metadata.return_value = identity.User(), metadata - - client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_user_rest_bad_request(request_type=identity.GetUserRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'users/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_user(request) - - -@pytest.mark.parametrize("request_type", [ - identity.GetUserRequest, - dict, -]) -def test_get_user_rest_call_success(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'users/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - ) - - # 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 = identity.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_user(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_rest_interceptors(null_interceptor): - transport = transports.IdentityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), - ) - client = IdentityClient(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.IdentityRestInterceptor, "post_get_user") as post, \ - mock.patch.object(transports.IdentityRestInterceptor, "post_get_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IdentityRestInterceptor, "pre_get_user") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = identity.GetUserRequest.pb(identity.GetUserRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = identity.User.to_json(identity.User()) - req.return_value.content = return_value - - request = identity.GetUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = identity.User() - post_with_metadata.return_value = identity.User(), metadata - - client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_user_rest_bad_request(request_type=identity.UpdateUserRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'user': {'name': 'users/sample1'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_user(request) - - -@pytest.mark.parametrize("request_type", [ - identity.UpdateUserRequest, - dict, -]) -def test_update_user_rest_call_success(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'user': {'name': 'users/sample1'}} - request_init["user"] = {'name': 'users/sample1', 'display_name': 'display_name_value', 'email': 'email_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'age': 301, 'height_feet': 0.1148, 'nickname': 'nickname_value', 'enable_notifications': 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 = identity.UpdateUserRequest.meta.fields["user"] - - 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["user"].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["user"][field])): - del request_init["user"][field][i][subfield] - else: - del request_init["user"][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 = identity.User( - name='name_value', - display_name='display_name_value', - email='email_value', - age=301, - height_feet=0.1148, - nickname='nickname_value', - enable_notifications=True, - ) - - # 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 = identity.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_user(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, identity.User) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.email == 'email_value' - assert response.age == 301 - assert math.isclose(response.height_feet, 0.1148, rel_tol=1e-6) - assert response.nickname == 'nickname_value' - assert response.enable_notifications is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_rest_interceptors(null_interceptor): - transport = transports.IdentityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), - ) - client = IdentityClient(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.IdentityRestInterceptor, "post_update_user") as post, \ - mock.patch.object(transports.IdentityRestInterceptor, "post_update_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IdentityRestInterceptor, "pre_update_user") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = identity.UpdateUserRequest.pb(identity.UpdateUserRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = identity.User.to_json(identity.User()) - req.return_value.content = return_value - - request = identity.UpdateUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = identity.User() - post_with_metadata.return_value = identity.User(), metadata - - client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_user_rest_bad_request(request_type=identity.DeleteUserRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'users/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_user(request) - - -@pytest.mark.parametrize("request_type", [ - identity.DeleteUserRequest, - dict, -]) -def test_delete_user_rest_call_success(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'users/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_user(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_user_rest_interceptors(null_interceptor): - transport = transports.IdentityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), - ) - client = IdentityClient(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.IdentityRestInterceptor, "pre_delete_user") as pre: - pre.assert_not_called() - pb_message = identity.DeleteUserRequest.pb(identity.DeleteUserRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = identity.DeleteUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_list_users_rest_bad_request(request_type=identity.ListUsersRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_users(request) - - -@pytest.mark.parametrize("request_type", [ - identity.ListUsersRequest, - dict, -]) -def test_list_users_rest_call_success(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = identity.ListUsersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = identity.ListUsersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_users(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_users_rest_interceptors(null_interceptor): - transport = transports.IdentityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IdentityRestInterceptor(), - ) - client = IdentityClient(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.IdentityRestInterceptor, "post_list_users") as post, \ - mock.patch.object(transports.IdentityRestInterceptor, "post_list_users_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IdentityRestInterceptor, "pre_list_users") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = identity.ListUsersRequest.pb(identity.ListUsersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = identity.ListUsersResponse.to_json(identity.ListUsersResponse()) - req.return_value.content = return_value - - request = identity.ListUsersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = identity.ListUsersResponse() - post_with_metadata.return_value = identity.ListUsersResponse(), metadata - - client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_initialize_client_w_rest(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_user_empty_call_rest(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - client.create_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.CreateUserRequest() - assert args[0] == request_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_user_empty_call_rest(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - client.get_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.GetUserRequest() - assert args[0] == request_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_user_empty_call_rest(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - client.update_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.UpdateUserRequest() - assert args[0] == request_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_user_empty_call_rest(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.DeleteUserRequest() - assert args[0] == request_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_users_empty_call_rest(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - client.list_users(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = identity.ListUsersRequest() - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.IdentityGrpcTransport, - ) - -def test_identity_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.IdentityTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_identity_base_transport(): - # Instantiate the base transport. - with mock.patch('google.showcase_v1beta1.services.identity.transports.IdentityTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.IdentityTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_user', - 'get_user', - 'update_user', - 'delete_user', - 'list_users', - '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() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_identity_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.showcase_v1beta1.services.identity.transports.IdentityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IdentityTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_identity_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.showcase_v1beta1.services.identity.transports.IdentityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IdentityTransport() - adc.assert_called_once() - - -def test_identity_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) - IdentityClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IdentityGrpcTransport, - transports.IdentityGrpcAsyncIOTransport, - ], -) -def test_identity_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IdentityGrpcTransport, - transports.IdentityGrpcAsyncIOTransport, - transports.IdentityRestTransport, - ], -) -def test_identity_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.IdentityGrpcTransport, grpc_helpers), - (transports.IdentityGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_identity_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( - "localhost:7469", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="localhost:7469", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.IdentityGrpcTransport, transports.IdentityGrpcAsyncIOTransport]) -def test_identity_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_identity_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.IdentityRestTransport ( - 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_identity_host_no_port(transport_name): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='localhost'), - transport=transport_name, - ) - assert client.transport._host == ( - 'localhost:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://localhost' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_identity_host_with_port(transport_name): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='localhost:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'localhost:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://localhost:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_identity_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = IdentityClient( - credentials=creds1, - transport=transport_name, - ) - client2 = IdentityClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_user._session - session2 = client2.transport.create_user._session - assert session1 != session2 - session1 = client1.transport.get_user._session - session2 = client2.transport.get_user._session - assert session1 != session2 - session1 = client1.transport.update_user._session - session2 = client2.transport.update_user._session - assert session1 != session2 - session1 = client1.transport.delete_user._session - session2 = client2.transport.delete_user._session - assert session1 != session2 - session1 = client1.transport.list_users._session - session2 = client2.transport.list_users._session - assert session1 != session2 -def test_identity_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.IdentityGrpcTransport( - 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_identity_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.IdentityGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize("transport_class", [transports.IdentityGrpcTransport, transports.IdentityGrpcAsyncIOTransport]) -def test_identity_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.IdentityGrpcTransport, transports.IdentityGrpcAsyncIOTransport]) -def test_identity_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_user_path(): - user = "squid" - expected = "users/{user}".format(user=user, ) - actual = IdentityClient.user_path(user) - assert expected == actual - - -def test_parse_user_path(): - expected = { - "user": "clam", - } - path = IdentityClient.user_path(**expected) - - # Check that the path construction is reversible. - actual = IdentityClient.parse_user_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = IdentityClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = IdentityClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = IdentityClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = IdentityClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = IdentityClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = IdentityClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = IdentityClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = IdentityClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = IdentityClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = IdentityClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = IdentityClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = IdentityClient.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 = IdentityClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = IdentityClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = IdentityClient.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.IdentityTransport, '_prep_wrapped_messages') as prep: - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.IdentityTransport, '_prep_wrapped_messages') as prep: - transport_class = IdentityClient.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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_delete_operation_flattened(): - client = IdentityClient( - 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 - - client.delete_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() - -@pytest.mark.asyncio -async def test_delete_operation_flattened_async(): - client = IdentityAsyncClient( - 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 - ) - await client.delete_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() - - -def test_cancel_operation(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_cancel_operation_flattened(): - client = IdentityClient( - 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 - - client.cancel_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() - -@pytest.mark.asyncio -async def test_cancel_operation_flattened_async(): - client = IdentityAsyncClient( - 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 - ) - await client.cancel_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() - - -def test_get_operation(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_get_operation_flattened(): - client = IdentityClient( - 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() - - client.get_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() - -@pytest.mark.asyncio -async def test_get_operation_flattened_async(): - client = IdentityAsyncClient( - 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() - ) - await client.get_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() - - -def test_list_operations(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_operations_flattened(): - client = IdentityClient( - 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() - - client.list_operations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() - -@pytest.mark.asyncio -async def test_list_operations_flattened_async(): - client = IdentityAsyncClient( - 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() - ) - await client.list_operations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() - - -def test_list_locations(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_list_locations_flattened(): - client = IdentityClient( - 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() - - client.list_locations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() - -@pytest.mark.asyncio -async def test_list_locations_flattened_async(): - client = IdentityAsyncClient( - 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() - ) - await client.list_locations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() - - -def test_get_location(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_get_location_flattened(): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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() - - client.get_location() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() - -@pytest.mark.asyncio -async def test_get_location_flattened_async(): - client = IdentityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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() - ) - await client.get_location() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() - - -def test_set_iam_policy(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_set_iam_policy_flattened(): - client = IdentityClient( - 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() - - client.set_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = IdentityAsyncClient( - 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() - ) - - await client.set_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -def test_get_iam_policy(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_get_iam_policy_flattened(): - client = IdentityClient( - 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() - - client.get_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = IdentityAsyncClient( - 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() - ) - - await client.get_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -def test_test_iam_permissions(transport: str = "grpc"): - client = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = IdentityAsyncClient( - 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 = IdentityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityAsyncClient( - 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_test_iam_permissions_flattened(): - client = IdentityClient( - 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() - - client.test_iam_permissions() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = IdentityAsyncClient( - 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() - ) - - await client.test_iam_permissions() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_transport_close_grpc(): - client = IdentityClient( - 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 = IdentityAsyncClient( - 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 = IdentityClient( - 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 = IdentityClient( - 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", [ - (IdentityClient, transports.IdentityGrpcTransport), - (IdentityAsyncClient, transports.IdentityGrpcAsyncIOTransport), -]) -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/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py b/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py deleted file mode 100644 index c39840595a01..000000000000 --- a/packages/gapic-generator/generated_showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py +++ /dev/null @@ -1,11873 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 asyncio -import re -from unittest import mock -from unittest.mock import AsyncMock - -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 collections.abc import Sequence, Mapping -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 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.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.showcase_v1beta1.services.messaging import MessagingAsyncClient -from google.showcase_v1beta1.services.messaging import MessagingClient -from google.showcase_v1beta1.services.messaging import pagers -from google.showcase_v1beta1.services.messaging import transports -from google.showcase_v1beta1.types import messaging -import google.api_core.operation_async as operation_async # type: ignore -import google.auth -import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) -_UUID4_RE = re.compile(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}") - - -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 - - -@pytest.fixture(autouse=True) -def set_event_loop(): - try: - asyncio.get_running_loop() - yield - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - yield - finally: - loop.close() - asyncio.set_event_loop(None) - - -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" - custom_endpoint = ".custom" - - assert MessagingClient._get_default_mtls_endpoint(None) is None - assert MessagingClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert MessagingClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert MessagingClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert MessagingClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert MessagingClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - assert MessagingClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint - -def test__read_environment_variables(): - assert MessagingClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert MessagingClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert MessagingClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with pytest.raises(ValueError) as excinfo: - MessagingClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - else: - assert MessagingClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert MessagingClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert MessagingClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert MessagingClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - MessagingClient._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 MessagingClient._read_environment_variables() == (False, "auto", "foo.com") - - -def test_use_client_cert_effective(): - # Test case 1: Test when `should_use_client_cert` returns True. - # We mock the `should_use_client_cert` function to simulate a scenario where - # the google-auth library supports automatic mTLS and determines that a - # client certificate should be used. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): - assert MessagingClient._use_client_cert_effective() is True - - # Test case 2: Test when `should_use_client_cert` returns False. - # We mock the `should_use_client_cert` function to simulate a scenario where - # the google-auth library supports automatic mTLS and determines that a - # client certificate should NOT be used. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): - assert MessagingClient._use_client_cert_effective() is False - - # Test case 3: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert MessagingClient._use_client_cert_effective() is True - - # Test case 4: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert MessagingClient._use_client_cert_effective() is False - - # Test case 5: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): - assert MessagingClient._use_client_cert_effective() is True - - # Test case 6: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): - assert MessagingClient._use_client_cert_effective() is False - - # Test case 7: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): - assert MessagingClient._use_client_cert_effective() is True - - # Test case 8: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): - assert MessagingClient._use_client_cert_effective() is False - - # Test case 9: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. - # In this case, the method should return False, which is the default value. - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, clear=True): - assert MessagingClient._use_client_cert_effective() is False - - # Test case 10: Test when `should_use_client_cert` is unavailable and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. - # The method should raise a ValueError as the environment variable must be either - # "true" or "false". - if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): - with pytest.raises(ValueError): - MessagingClient._use_client_cert_effective() - - # Test case 11: Test when `should_use_client_cert` is available and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. - # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): - assert MessagingClient._use_client_cert_effective() is False - - # Test case 12: Test when `should_use_client_cert` is available and the - # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, - # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): - with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): - assert MessagingClient._use_client_cert_effective() is False - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert MessagingClient._get_client_cert_source(None, False) is None - assert MessagingClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert MessagingClient._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 MessagingClient._get_client_cert_source(None, True) is mock_default_cert_source - assert MessagingClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) -@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = MessagingClient._DEFAULT_UNIVERSE - default_endpoint = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert MessagingClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert MessagingClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == MessagingClient.DEFAULT_MTLS_ENDPOINT - assert MessagingClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert MessagingClient._get_api_endpoint(None, None, default_universe, "always") == MessagingClient.DEFAULT_MTLS_ENDPOINT - assert MessagingClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == MessagingClient.DEFAULT_MTLS_ENDPOINT - assert MessagingClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert MessagingClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - MessagingClient._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 MessagingClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert MessagingClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert MessagingClient._get_universe_domain(None, None) == MessagingClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - MessagingClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = MessagingClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = MessagingClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -def test__setup_request_id(): - class MockRequest: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - def __contains__(self, key): - return hasattr(self, key) - - class MockProtoRequest: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - def HasField(self, key): - return hasattr(self, key) - - # Test with proto3 optional field not in request - request = MockRequest() - MessagingClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with proto3 optional field already in request - request = MockRequest(request_id="already_set") - MessagingClient._setup_request_id(request, "request_id", True) - assert request.request_id == "already_set" - - # Test with non-proto3 optional field empty - request = MockRequest(request_id="") - MessagingClient._setup_request_id(request, "request_id", False) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with non-proto3 optional field already set - request = MockRequest(request_id="already_set") - MessagingClient._setup_request_id(request, "request_id", False) - assert request.request_id == "already_set" - - # Test with proto3 optional field not in request (MockProtoRequest) - request = MockProtoRequest() - MessagingClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with proto3 optional field already in request (MockProtoRequest) - request = MockProtoRequest(request_id="already_set") - MessagingClient._setup_request_id(request, "request_id", True) - assert request.request_id == "already_set" - - # Test with ValueError - class MockValueErrorRequest: - def HasField(self, key): - raise ValueError("Mismatched field") - def __contains__(self, key): - return hasattr(self, key) - - request = MockValueErrorRequest() - MessagingClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request.request_id) - - # Test with dict and proto3 optional field not in request - request = {} - MessagingClient._setup_request_id(request, "request_id", True) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) - - # Test with dict and proto3 optional field already in request - request = {"request_id": "already_set"} - MessagingClient._setup_request_id(request, "request_id", True) - assert request["request_id"] == "already_set" - - # Test with dict and non-proto3 optional field empty - request = {"request_id": ""} - MessagingClient._setup_request_id(request, "request_id", False) - assert re.match(r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}", request["request_id"]) - - # Test with dict and non-proto3 optional field already set - request = {"request_id": "already_set"} - MessagingClient._setup_request_id(request, "request_id", False) - assert request["request_id"] == "already_set" - -@pytest.mark.parametrize("client_class,transport_name", [ - (MessagingClient, "grpc"), - (MessagingAsyncClient, "grpc_asyncio"), - (MessagingClient, "rest"), -]) -def test_messaging_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 == ( - 'localhost:7469' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://localhost:7469' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.MessagingGrpcTransport, "grpc"), - (transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.MessagingRestTransport, "rest"), -]) -def test_messaging_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", [ - (MessagingClient, "grpc"), - (MessagingAsyncClient, "grpc_asyncio"), - (MessagingClient, "rest"), -]) -def test_messaging_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 == ( - 'localhost:7469' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://localhost:7469' - ) - - -def test_messaging_client_get_transport_class(): - transport = MessagingClient.get_transport_class() - available_transports = [ - transports.MessagingGrpcTransport, - transports.MessagingRestTransport, - ] - assert transport in available_transports - - transport = MessagingClient.get_transport_class("grpc") - assert transport == transports.MessagingGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (MessagingClient, transports.MessagingGrpcTransport, "grpc"), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio"), - (MessagingClient, transports.MessagingRestTransport, "rest"), -]) -@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) -@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) -def test_messaging_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(MessagingClient, '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(MessagingClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (MessagingClient, transports.MessagingGrpcTransport, "grpc", "true"), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (MessagingClient, transports.MessagingGrpcTransport, "grpc", "false"), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (MessagingClient, transports.MessagingRestTransport, "rest", "true"), - (MessagingClient, transports.MessagingRestTransport, "rest", "false"), -]) -@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) -@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_messaging_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", [ - MessagingClient, MessagingAsyncClient -]) -@mock.patch.object(MessagingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MessagingClient)) -@mock.patch.object(MessagingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MessagingAsyncClient)) -def test_messaging_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. - test_cases = [ - ( - # With workloads present in config, mTLS is enabled. - { - "version": 1, - "cert_configs": { - "workload": { - "cert_path": "path/to/cert/file", - "key_path": "path/to/key/file", - } - }, - }, - mock_client_cert_source, - ), - ( - # With workloads not present in config, mTLS is disabled. - { - "version": 1, - "cert_configs": {}, - }, - None, - ), - ] - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - for config_data, expected_cert_source in test_cases: - env = os.environ.copy() - env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) - with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source - - # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). - test_cases = [ - ( - # With workloads present in config, mTLS is enabled. - { - "version": 1, - "cert_configs": { - "workload": { - "cert_path": "path/to/cert/file", - "key_path": "path/to/key/file", - } - }, - }, - mock_client_cert_source, - ), - ( - # With workloads not present in config, mTLS is disabled. - { - "version": 1, - "cert_configs": {}, - }, - None, - ), - ] - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - for config_data, expected_cert_source in test_cases: - env = os.environ.copy() - env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") - with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - -@pytest.mark.parametrize("client_class", [ - MessagingClient, MessagingAsyncClient -]) -@mock.patch.object(MessagingClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingClient)) -@mock.patch.object(MessagingAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(MessagingAsyncClient)) -def test_messaging_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = MessagingClient._DEFAULT_UNIVERSE - default_endpoint = MessagingClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = MessagingClient._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", [ - (MessagingClient, transports.MessagingGrpcTransport, "grpc"), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio"), - (MessagingClient, transports.MessagingRestTransport, "rest"), -]) -def test_messaging_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", [ - (MessagingClient, transports.MessagingGrpcTransport, "grpc", grpc_helpers), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (MessagingClient, transports.MessagingRestTransport, "rest", None), -]) -def test_messaging_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_messaging_client_client_options_from_dict(): - with mock.patch('google.showcase_v1beta1.services.messaging.transports.MessagingGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = MessagingClient( - 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", [ - (MessagingClient, transports.MessagingGrpcTransport, "grpc", grpc_helpers), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_messaging_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( - "localhost:7469", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="localhost:7469", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.CreateRoomRequest(), - {}, -]) -def test_create_room(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.create_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.CreateRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_room_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 = MessagingClient( - 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 = messaging.CreateRoomRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_room(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateRoomRequest( - ) - assert args[0] == request_msg - -def test_create_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - request = {} - client.create_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_room(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_room_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 = MessagingAsyncClient( - 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_room 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_room] = mock_rpc - - request = {} - await client.create_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_room(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 -@pytest.mark.parametrize("request_type", [ - messaging.CreateRoomRequest(), - {}, -]) -async def test_create_room_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.CreateRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_room_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_room( - display_name='display_name_value', - description='description_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].room.display_name - mock_val = 'display_name_value' - assert arg == mock_val - arg = args[0].room.description - mock_val = 'description_value' - assert arg == mock_val - - -def test_create_room_flattened_error(): - client = MessagingClient( - credentials=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_room( - messaging.CreateRoomRequest(), - display_name='display_name_value', - description='description_value', - ) - -@pytest.mark.asyncio -async def test_create_room_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_room( - display_name='display_name_value', - description='description_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].room.display_name - mock_val = 'display_name_value' - assert arg == mock_val - arg = args[0].room.description - mock_val = 'description_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_room_flattened_error_async(): - client = MessagingAsyncClient( - 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_room( - messaging.CreateRoomRequest(), - display_name='display_name_value', - description='description_value', - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.GetRoomRequest(), - {}, -]) -def test_get_room(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.GetRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_room_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 = MessagingClient( - 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 = messaging.GetRoomRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_room(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetRoomRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_get_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - request = {} - client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_room(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_room_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 = MessagingAsyncClient( - 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_room 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_room] = mock_rpc - - request = {} - await client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_room(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 -@pytest.mark.parametrize("request_type", [ - messaging.GetRoomRequest(), - {}, -]) -async def test_get_room_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.GetRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_get_room_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.GetRoomRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - call.return_value = messaging.Room() - client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_room_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.GetRoomRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) - await client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_room_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_room( - name='name_value', - ) - - # Establish that the 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_room_flattened_error(): - client = MessagingClient( - credentials=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_room( - messaging.GetRoomRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_room_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_room( - name='name_value', - ) - - # Establish that 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_room_flattened_error_async(): - client = MessagingAsyncClient( - 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_room( - messaging.GetRoomRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.UpdateRoomRequest(), - {}, -]) -def test_update_room(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.UpdateRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_room_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 = MessagingClient( - 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 = messaging.UpdateRoomRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_room(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateRoomRequest( - ) - assert args[0] == request_msg - -def test_update_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - request = {} - client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_room(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_room_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 = MessagingAsyncClient( - 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_room 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_room] = mock_rpc - - request = {} - await client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_room(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 -@pytest.mark.parametrize("request_type", [ - messaging.UpdateRoomRequest(), - {}, -]) -async def test_update_room_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.UpdateRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_update_room_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.UpdateRoomRequest() - - request.room.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - call.return_value = messaging.Room() - client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'room.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_room_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.UpdateRoomRequest() - - request.room.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room()) - await client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'room.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - messaging.DeleteRoomRequest(), - {}, -]) -def test_delete_room(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.DeleteRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_room_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 = MessagingClient( - 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 = messaging.DeleteRoomRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_room(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteRoomRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_delete_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - request = {} - client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_room(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_room_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 = MessagingAsyncClient( - 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_room 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_room] = mock_rpc - - request = {} - await client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_room(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 -@pytest.mark.parametrize("request_type", [ - messaging.DeleteRoomRequest(), - {}, -]) -async def test_delete_room_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.DeleteRoomRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_room_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.DeleteRoomRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - call.return_value = None - client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_room_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.DeleteRoomRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_room_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_room( - name='name_value', - ) - - # Establish that the 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_room_flattened_error(): - client = MessagingClient( - credentials=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_room( - messaging.DeleteRoomRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_room_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_room( - name='name_value', - ) - - # Establish that 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_room_flattened_error_async(): - client = MessagingAsyncClient( - 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_room( - messaging.DeleteRoomRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.ListRoomsRequest(), - {}, -]) -def test_list_rooms(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_rooms), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.ListRoomsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_rooms(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.ListRoomsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRoomsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_rooms_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 = MessagingClient( - 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 = messaging.ListRoomsRequest( - 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_rooms), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_rooms(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListRoomsRequest( - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_list_rooms_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 = MessagingClient( - 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_rooms 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_rooms] = mock_rpc - request = {} - client.list_rooms(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_rooms(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_rooms_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 = MessagingAsyncClient( - 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_rooms 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_rooms] = mock_rpc - - request = {} - await client.list_rooms(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_rooms(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 -@pytest.mark.parametrize("request_type", [ - messaging.ListRoomsRequest(), - {}, -]) -async def test_list_rooms_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_rooms), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListRoomsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_rooms(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.ListRoomsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRoomsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_rooms_pager(transport_name: str = "grpc"): - client = MessagingClient( - 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_rooms), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - messaging.Room(), - ], - next_page_token='abc', - ), - messaging.ListRoomsResponse( - rooms=[], - next_page_token='def', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - ], - next_page_token='ghi', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_rooms(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, messaging.Room) - for i in results) -def test_list_rooms_pages(transport_name: str = "grpc"): - client = MessagingClient( - 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_rooms), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - messaging.Room(), - ], - next_page_token='abc', - ), - messaging.ListRoomsResponse( - rooms=[], - next_page_token='def', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - ], - next_page_token='ghi', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - ], - ), - RuntimeError, - ) - pages = list(client.list_rooms(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_rooms_async_pager(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_rooms), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - messaging.Room(), - ], - next_page_token='abc', - ), - messaging.ListRoomsResponse( - rooms=[], - next_page_token='def', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - ], - next_page_token='ghi', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_rooms(request={},) - assert async_pager.next_page_token == 'abc' - assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, messaging.Room) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_rooms_async_pages(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_rooms), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - messaging.Room(), - ], - next_page_token='abc', - ), - messaging.ListRoomsResponse( - rooms=[], - next_page_token='def', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - ], - next_page_token='ghi', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.list_rooms(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", [ - messaging.CreateBlurbRequest(), - {}, -]) -def test_create_blurb(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb( - name='name_value', - user='user_value', - text='text_value', - legacy_room_id='legacy_room_id_value', - ) - response = client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.CreateBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - - -def test_create_blurb_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 = MessagingClient( - 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 = messaging.CreateBlurbRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_blurb(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateBlurbRequest( - parent='parent_value', - ) - assert args[0] == request_msg - -def test_create_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - request = {} - client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_blurb(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_blurb_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 = MessagingAsyncClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - await client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_blurb(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 -@pytest.mark.parametrize("request_type", [ - messaging.CreateBlurbRequest(), - {}, -]) -async def test_create_blurb_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( - name='name_value', - user='user_value', - )) - response = await client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.CreateBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - -def test_create_blurb_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.CreateBlurbRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - call.return_value = messaging.Blurb() - client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_blurb_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.CreateBlurbRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) - await client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_blurb_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_blurb( - parent='parent_value', - user='user_value', - text='text_value', - image=b'image_blob', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].blurb.user - mock_val = 'user_value' - assert arg == mock_val - assert args[0].blurb.image == b'image_blob' - - -def test_create_blurb_flattened_error(): - client = MessagingClient( - credentials=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_blurb( - messaging.CreateBlurbRequest(), - parent='parent_value', - user='user_value', - text='text_value', - image=b'image_blob', - ) - -@pytest.mark.asyncio -async def test_create_blurb_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_blurb( - parent='parent_value', - user='user_value', - text='text_value', - image=b'image_blob', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].blurb.user - mock_val = 'user_value' - assert arg == mock_val - assert args[0].blurb.image == b'image_blob' - -@pytest.mark.asyncio -async def test_create_blurb_flattened_error_async(): - client = MessagingAsyncClient( - 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_blurb( - messaging.CreateBlurbRequest(), - parent='parent_value', - user='user_value', - text='text_value', - image=b'image_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.GetBlurbRequest(), - {}, -]) -def test_get_blurb(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb( - name='name_value', - user='user_value', - text='text_value', - legacy_room_id='legacy_room_id_value', - ) - response = client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.GetBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - - -def test_get_blurb_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 = MessagingClient( - 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 = messaging.GetBlurbRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_blurb(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetBlurbRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_get_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - request = {} - client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_blurb(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_blurb_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 = MessagingAsyncClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - await client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_blurb(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 -@pytest.mark.parametrize("request_type", [ - messaging.GetBlurbRequest(), - {}, -]) -async def test_get_blurb_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( - name='name_value', - user='user_value', - )) - response = await client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.GetBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - -def test_get_blurb_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.GetBlurbRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - call.return_value = messaging.Blurb() - client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_blurb_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.GetBlurbRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) - await client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_blurb_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_blurb( - name='name_value', - ) - - # Establish that the 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_blurb_flattened_error(): - client = MessagingClient( - credentials=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_blurb( - messaging.GetBlurbRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_blurb_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_blurb( - name='name_value', - ) - - # Establish that 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_blurb_flattened_error_async(): - client = MessagingAsyncClient( - 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_blurb( - messaging.GetBlurbRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.UpdateBlurbRequest(), - {}, -]) -def test_update_blurb(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.Blurb( - name='name_value', - user='user_value', - text='text_value', - legacy_room_id='legacy_room_id_value', - ) - response = client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.UpdateBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - - -def test_update_blurb_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 = MessagingClient( - 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 = messaging.UpdateBlurbRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_blurb(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateBlurbRequest( - ) - assert args[0] == request_msg - -def test_update_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - request = {} - client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_blurb(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_blurb_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 = MessagingAsyncClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - await client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_blurb(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 -@pytest.mark.parametrize("request_type", [ - messaging.UpdateBlurbRequest(), - {}, -]) -async def test_update_blurb_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( - name='name_value', - user='user_value', - )) - response = await client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.UpdateBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - -def test_update_blurb_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.UpdateBlurbRequest() - - request.blurb.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - call.return_value = messaging.Blurb() - client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'blurb.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_blurb_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.UpdateBlurbRequest() - - request.blurb.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb()) - await client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'blurb.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - messaging.DeleteBlurbRequest(), - {}, -]) -def test_delete_blurb(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.DeleteBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_blurb_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 = MessagingClient( - 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 = messaging.DeleteBlurbRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_blurb(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteBlurbRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_delete_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - request = {} - client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_blurb(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_blurb_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 = MessagingAsyncClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - await client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_blurb(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 -@pytest.mark.parametrize("request_type", [ - messaging.DeleteBlurbRequest(), - {}, -]) -async def test_delete_blurb_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.DeleteBlurbRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_blurb_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.DeleteBlurbRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - call.return_value = None - client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_blurb_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.DeleteBlurbRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_blurb_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_blurb( - name='name_value', - ) - - # Establish that the 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_blurb_flattened_error(): - client = MessagingClient( - credentials=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_blurb( - messaging.DeleteBlurbRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_blurb_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_blurb( - name='name_value', - ) - - # Establish that 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_blurb_flattened_error_async(): - client = MessagingAsyncClient( - 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_blurb( - messaging.DeleteBlurbRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - messaging.ListBlurbsRequest(), - {}, -]) -def test_list_blurbs(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.ListBlurbsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.ListBlurbsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBlurbsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_blurbs_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 = MessagingClient( - 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 = messaging.ListBlurbsRequest( - 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_blurbs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_blurbs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListBlurbsRequest( - parent='parent_value', - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_list_blurbs_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 = MessagingClient( - 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_blurbs 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_blurbs] = mock_rpc - request = {} - client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_blurbs(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_blurbs_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 = MessagingAsyncClient( - 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_blurbs 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_blurbs] = mock_rpc - - request = {} - await client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_blurbs(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 -@pytest.mark.parametrize("request_type", [ - messaging.ListBlurbsRequest(), - {}, -]) -async def test_list_blurbs_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.ListBlurbsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBlurbsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_blurbs_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.ListBlurbsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - call.return_value = messaging.ListBlurbsResponse() - client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_blurbs_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.ListBlurbsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse()) - await client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_blurbs_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.ListBlurbsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_blurbs( - 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_blurbs_flattened_error(): - client = MessagingClient( - credentials=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_blurbs( - messaging.ListBlurbsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_blurbs_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.ListBlurbsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_blurbs( - 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_blurbs_flattened_error_async(): - client = MessagingAsyncClient( - 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_blurbs( - messaging.ListBlurbsRequest(), - parent='parent_value', - ) - - -def test_list_blurbs_pager(transport_name: str = "grpc"): - client = MessagingClient( - 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_blurbs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - messaging.Blurb(), - ], - next_page_token='abc', - ), - messaging.ListBlurbsResponse( - blurbs=[], - next_page_token='def', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - ], - next_page_token='ghi', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_blurbs(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, messaging.Blurb) - for i in results) -def test_list_blurbs_pages(transport_name: str = "grpc"): - client = MessagingClient( - 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_blurbs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - messaging.Blurb(), - ], - next_page_token='abc', - ), - messaging.ListBlurbsResponse( - blurbs=[], - next_page_token='def', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - ], - next_page_token='ghi', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - ], - ), - RuntimeError, - ) - pages = list(client.list_blurbs(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_blurbs_async_pager(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - messaging.Blurb(), - ], - next_page_token='abc', - ), - messaging.ListBlurbsResponse( - blurbs=[], - next_page_token='def', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - ], - next_page_token='ghi', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_blurbs(request={},) - assert async_pager.next_page_token == 'abc' - assert str(async_pager).startswith(f'{async_pager.__class__.__name__}<') - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, messaging.Blurb) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_blurbs_async_pages(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - messaging.Blurb(), - ], - next_page_token='abc', - ), - messaging.ListBlurbsResponse( - blurbs=[], - next_page_token='def', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - ], - next_page_token='ghi', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.list_blurbs(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", [ - messaging.SearchBlurbsRequest(), - {}, -]) -def test_search_blurbs(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.search_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.SearchBlurbsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_search_blurbs_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 = MessagingClient( - 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 = messaging.SearchBlurbsRequest( - query='query_value', - 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.search_blurbs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_blurbs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.SearchBlurbsRequest( - query='query_value', - parent='parent_value', - page_token='page_token_value', - ) - assert args[0] == request_msg - -def test_search_blurbs_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 = MessagingClient( - 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.search_blurbs 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.search_blurbs] = mock_rpc - request = {} - client.search_blurbs(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.search_blurbs(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_search_blurbs_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 = MessagingAsyncClient( - 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.search_blurbs 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.search_blurbs] = mock_rpc - - request = {} - await client.search_blurbs(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.search_blurbs(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 -@pytest.mark.parametrize("request_type", [ - messaging.SearchBlurbsRequest(), - {}, -]) -async def test_search_blurbs_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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.search_blurbs), - '__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.search_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.SearchBlurbsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - -def test_search_blurbs_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.SearchBlurbsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.search_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_blurbs_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.SearchBlurbsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.search_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_search_blurbs_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__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.search_blurbs( - parent='parent_value', - query='query_value', - ) - - # Establish that the 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].query - mock_val = 'query_value' - assert arg == mock_val - - -def test_search_blurbs_flattened_error(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_blurbs( - messaging.SearchBlurbsRequest(), - parent='parent_value', - query='query_value', - ) - -@pytest.mark.asyncio -async def test_search_blurbs_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__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.search_blurbs( - parent='parent_value', - query='query_value', - ) - - # Establish that 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].query - mock_val = 'query_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_blurbs_flattened_error_async(): - client = MessagingAsyncClient( - 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.search_blurbs( - messaging.SearchBlurbsRequest(), - parent='parent_value', - query='query_value', - ) - - -def test_search_blurbs_raw_page_lro(): - response = messaging.SearchBlurbsResponse() - assert response.raw_page is response - -@pytest.mark.parametrize("request_type", [ - messaging.StreamBlurbsRequest(), - {}, -]) -def test_stream_blurbs(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([messaging.StreamBlurbsResponse()]) - response = client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = messaging.StreamBlurbsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, messaging.StreamBlurbsResponse) - - -def test_stream_blurbs_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 = MessagingClient( - 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 = messaging.StreamBlurbsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stream_blurbs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.StreamBlurbsRequest( - name='name_value', - ) - assert args[0] == request_msg - -def test_stream_blurbs_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 = MessagingClient( - 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.stream_blurbs 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.stream_blurbs] = mock_rpc - request = {} - client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stream_blurbs(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_stream_blurbs_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 = MessagingAsyncClient( - 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.stream_blurbs 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.stream_blurbs] = mock_rpc - - request = {} - await client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.stream_blurbs(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 -@pytest.mark.parametrize("request_type", [ - messaging.StreamBlurbsRequest(), - {}, -]) -async def test_stream_blurbs_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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.stream_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) - response = await client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = messaging.StreamBlurbsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, messaging.StreamBlurbsResponse) - -def test_stream_blurbs_field_headers(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = messaging.StreamBlurbsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - call.return_value = iter([messaging.StreamBlurbsResponse()]) - client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_stream_blurbs_field_headers_async(): - client = MessagingAsyncClient( - 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 = messaging.StreamBlurbsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) - await client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - messaging.CreateBlurbRequest(), - {}, -]) -def test_send_blurbs(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = messaging.SendBlurbsResponse( - names=['names_value'], - ) - response = client.send_blurbs(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.SendBlurbsResponse) - assert response.names == ['names_value'] - -def test_send_blurbs_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 = MessagingClient( - 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.send_blurbs 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.send_blurbs] = mock_rpc - request = [{}] - client.send_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.send_blurbs(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_send_blurbs_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 = MessagingAsyncClient( - 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.send_blurbs 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.send_blurbs] = mock_rpc - - request = [{}] - await client.send_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.send_blurbs(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 -@pytest.mark.parametrize("request_type", [ - messaging.CreateBlurbRequest(), - {}, -]) -async def test_send_blurbs_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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 - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeStreamUnaryCall(messaging.SendBlurbsResponse( - names=['names_value'], - )) - response = await (await client.send_blurbs(iter(requests))) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.SendBlurbsResponse) - assert response.names == ['names_value'] - - -@pytest.mark.parametrize("request_type", [ - messaging.ConnectRequest(), - {}, -]) -def test_connect(request_type, transport: str = 'grpc'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.connect), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([messaging.StreamBlurbsResponse()]) - response = client.connect(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, messaging.StreamBlurbsResponse) - -def test_connect_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 = MessagingClient( - 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.connect 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.connect] = mock_rpc - request = [{}] - client.connect(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.connect(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_connect_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 = MessagingAsyncClient( - 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.connect 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.connect] = mock_rpc - - request = [{}] - await client.connect(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.connect(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 -@pytest.mark.parametrize("request_type", [ - messaging.ConnectRequest(), - {}, -]) -async def test_connect_async(request_type, transport: str = 'grpc_asyncio'): - client = MessagingAsyncClient( - 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 - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.connect), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) - response = await client.connect(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, messaging.StreamBlurbsResponse) - - -def test_create_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - - request = {} - client.create_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_room(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_room_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Room() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - display_name='display_name_value', - description='description_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 = messaging.Room.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_room(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/rooms" % client.transport._host, args[1]) - - -def test_create_room_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_room( - messaging.CreateRoomRequest(), - display_name='display_name_value', - description='description_value', - ) - - -def test_get_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - - request = {} - client.get_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_room(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_room_rest_required_fields(request_type=messaging.GetRoomRequest): - transport_class = transports.MessagingRestTransport - - 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_room._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_room._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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = messaging.Room() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = messaging.Room.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_room(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_get_room_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_room._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_room_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Room() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'rooms/sample1'} - - # 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 = messaging.Room.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_room(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=rooms/*}" % client.transport._host, args[1]) - - -def test_get_room_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_room( - messaging.GetRoomRequest(), - name='name_value', - ) - - -def test_update_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - - request = {} - client.update_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_room(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_room_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 = MessagingClient( - 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_room 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_room] = mock_rpc - - request = {} - client.delete_room(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_room(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_room_rest_required_fields(request_type=messaging.DeleteRoomRequest): - transport_class = transports.MessagingRestTransport - - 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_room._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_room._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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_room(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_delete_room_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_room._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_room_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'rooms/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_room(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=rooms/*}" % client.transport._host, args[1]) - - -def test_delete_room_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_room( - messaging.DeleteRoomRequest(), - name='name_value', - ) - - -def test_list_rooms_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 = MessagingClient( - 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_rooms 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_rooms] = mock_rpc - - request = {} - client.list_rooms(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_rooms(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_rooms_rest_pager(transport: str = 'rest'): - client = MessagingClient( - 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 = ( - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - messaging.Room(), - ], - next_page_token='abc', - ), - messaging.ListRoomsResponse( - rooms=[], - next_page_token='def', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - ], - next_page_token='ghi', - ), - messaging.ListRoomsResponse( - rooms=[ - messaging.Room(), - messaging.Room(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(messaging.ListRoomsResponse.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 = {} - - pager = client.list_rooms(request=sample_request) - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, messaging.Room) - for i in results) - - pages = list(client.list_rooms(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - client.create_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_blurb(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_blurb_rest_required_fields(request_type=messaging.CreateBlurbRequest): - transport_class = transports.MessagingRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_blurb._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_blurb._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = messaging.Blurb() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_blurb(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_create_blurb_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_blurb._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_create_blurb_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Blurb() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'rooms/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - user='user_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 = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_blurb(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=rooms/*}/blurbs" % client.transport._host, args[1]) - - -def test_create_blurb_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_blurb( - messaging.CreateBlurbRequest(), - parent='parent_value', - user='user_value', - text='text_value', - image=b'image_blob', - ) - - -def test_get_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - client.get_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_blurb(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_blurb_rest_required_fields(request_type=messaging.GetBlurbRequest): - transport_class = transports.MessagingRestTransport - - 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_blurb._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_blurb._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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = messaging.Blurb() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_blurb(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_get_blurb_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_blurb._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_blurb_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Blurb() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'rooms/sample1/blurbs/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_blurb(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=rooms/*/blurbs/*}" % client.transport._host, args[1]) - - -def test_get_blurb_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_blurb( - messaging.GetBlurbRequest(), - name='name_value', - ) - - -def test_update_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - client.update_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_blurb(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_blurb_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 = MessagingClient( - 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_blurb 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_blurb] = mock_rpc - - request = {} - client.delete_blurb(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_blurb(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_blurb_rest_required_fields(request_type=messaging.DeleteBlurbRequest): - transport_class = transports.MessagingRestTransport - - 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_blurb._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_blurb._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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_blurb(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_delete_blurb_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_blurb._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_blurb_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'rooms/sample1/blurbs/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_blurb(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=rooms/*/blurbs/*}" % client.transport._host, args[1]) - - -def test_delete_blurb_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_blurb( - messaging.DeleteBlurbRequest(), - name='name_value', - ) - - -def test_list_blurbs_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 = MessagingClient( - 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_blurbs 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_blurbs] = mock_rpc - - request = {} - client.list_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_blurbs(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_blurbs_rest_required_fields(request_type=messaging.ListBlurbsRequest): - transport_class = transports.MessagingRestTransport - - 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_blurbs._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_blurbs._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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = messaging.ListBlurbsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = messaging.ListBlurbsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_blurbs(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_list_blurbs_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_blurbs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_blurbs_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.ListBlurbsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'rooms/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = messaging.ListBlurbsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_blurbs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=rooms/*}/blurbs" % client.transport._host, args[1]) - - -def test_list_blurbs_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.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_blurbs( - messaging.ListBlurbsRequest(), - parent='parent_value', - ) - - -def test_list_blurbs_rest_pager(transport: str = 'rest'): - client = MessagingClient( - 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 = ( - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - messaging.Blurb(), - ], - next_page_token='abc', - ), - messaging.ListBlurbsResponse( - blurbs=[], - next_page_token='def', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - ], - next_page_token='ghi', - ), - messaging.ListBlurbsResponse( - blurbs=[ - messaging.Blurb(), - messaging.Blurb(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(messaging.ListBlurbsResponse.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': 'rooms/sample1'} - - pager = client.list_blurbs(request=sample_request) - - assert pager.next_page_token == 'abc' - assert str(pager).startswith(f'{pager.__class__.__name__}<') - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, messaging.Blurb) - for i in results) - - pages = list(client.list_blurbs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_search_blurbs_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 = MessagingClient( - 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.search_blurbs 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.search_blurbs] = mock_rpc - - request = {} - client.search_blurbs(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.search_blurbs(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_search_blurbs_rest_required_fields(request_type=messaging.SearchBlurbsRequest): - transport_class = transports.MessagingRestTransport - - request_init = {} - request_init["query"] = "" - 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()).search_blurbs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["query"] = 'query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_blurbs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "query" in jsonified_request - assert jsonified_request["query"] == 'query_value' - - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.search_blurbs(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_search_blurbs_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_blurbs._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("query", ))) - - -def test_search_blurbs_rest_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'rooms/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - query='query_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.search_blurbs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=rooms/*}/blurbs:search" % client.transport._host, args[1]) - - -def test_search_blurbs_rest_flattened_error(transport: str = 'rest'): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_blurbs( - messaging.SearchBlurbsRequest(), - parent='parent_value', - query='query_value', - ) - - -def test_stream_blurbs_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 = MessagingClient( - 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.stream_blurbs 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.stream_blurbs] = mock_rpc - - request = {} - client.stream_blurbs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stream_blurbs(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_stream_blurbs_rest_required_fields(request_type=messaging.StreamBlurbsRequest): - transport_class = transports.MessagingRestTransport - - 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()).stream_blurbs._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()).stream_blurbs._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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = messaging.StreamBlurbsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.StreamBlurbsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.stream_blurbs(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert sorted(expected_params) == sorted(actual_params) - - -def test_stream_blurbs_rest_unset_required_fields(): - transport = transports.MessagingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stream_blurbs._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "expireTime", ))) - - -def test_send_blurbs_rest_unimplemented(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = messaging.CreateBlurbRequest() - requests = [request] - with pytest.raises(NotImplementedError): - client.send_blurbs(requests) - - -def test_connect_rest_no_http_options(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = messaging.ConnectRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.connect(requests) - - -def test_connect_rest_error(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.connect({}) - assert ( - "Method Connect is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.MessagingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.MessagingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MessagingClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.MessagingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = MessagingClient( - 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 = MessagingClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.MessagingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MessagingClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.MessagingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = MessagingClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.MessagingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.MessagingGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.MessagingGrpcTransport, - transports.MessagingGrpcAsyncIOTransport, - transports.MessagingRestTransport, -]) -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 = MessagingClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_room_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - call.return_value = messaging.Room() - client.create_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateRoomRequest() - assert args[0] == request_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_room_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - call.return_value = messaging.Room() - client.get_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetRoomRequest() - assert args[0] == request_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_room_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - call.return_value = messaging.Room() - client.update_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateRoomRequest() - assert args[0] == request_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_room_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - call.return_value = None - client.delete_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteRoomRequest() - assert args[0] == request_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_rooms_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_rooms), - '__call__') as call: - call.return_value = messaging.ListRoomsResponse() - client.list_rooms(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListRoomsRequest() - assert args[0] == request_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_blurb_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - call.return_value = messaging.Blurb() - client.create_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateBlurbRequest() - assert args[0] == request_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_blurb_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - call.return_value = messaging.Blurb() - client.get_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetBlurbRequest() - assert args[0] == request_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_blurb_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - call.return_value = messaging.Blurb() - client.update_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateBlurbRequest() - assert args[0] == request_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_blurb_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - call.return_value = None - client.delete_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteBlurbRequest() - assert args[0] == request_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_blurbs_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - call.return_value = messaging.ListBlurbsResponse() - client.list_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListBlurbsRequest() - assert args[0] == request_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_search_blurbs_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.search_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.SearchBlurbsRequest() - assert args[0] == request_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_stream_blurbs_empty_call_grpc(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - call.return_value = iter([messaging.StreamBlurbsResponse()]) - client.stream_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.StreamBlurbsRequest() - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = MessagingAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_room_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - await client.create_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateRoomRequest() - assert args[0] == request_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_room_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - await client.get_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetRoomRequest() - assert args[0] == request_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_room_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - await client.update_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateRoomRequest() - assert args[0] == request_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_room_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteRoomRequest() - assert args[0] == request_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_rooms_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_rooms), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListRoomsResponse( - next_page_token='next_page_token_value', - )) - await client.list_rooms(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListRoomsRequest() - assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( - name='name_value', - user='user_value', - )) - await client.create_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateBlurbRequest() - assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( - name='name_value', - user='user_value', - )) - await client.get_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetBlurbRequest() - assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.Blurb( - name='name_value', - user='user_value', - )) - await client.update_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateBlurbRequest() - assert args[0] == request_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_blurb_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteBlurbRequest() - assert args[0] == request_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_blurbs_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(messaging.ListBlurbsResponse( - next_page_token='next_page_token_value', - )) - await client.list_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListBlurbsRequest() - assert args[0] == request_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_search_blurbs_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__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.search_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.SearchBlurbsRequest() - assert args[0] == request_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_stream_blurbs_empty_call_grpc_asyncio(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[messaging.StreamBlurbsResponse()]) - await client.stream_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.StreamBlurbsRequest() - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = MessagingClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_room_rest_bad_request(request_type=messaging.CreateRoomRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_room(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.CreateRoomRequest, - dict, -]) -def test_create_room_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.Room.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_room(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_room_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_create_room") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_create_room_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_create_room") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.CreateRoomRequest.pb(messaging.CreateRoomRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.Room.to_json(messaging.Room()) - req.return_value.content = return_value - - request = messaging.CreateRoomRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.Room() - post_with_metadata.return_value = messaging.Room(), metadata - - client.create_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_room_rest_bad_request(request_type=messaging.GetRoomRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_room(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.GetRoomRequest, - dict, -]) -def test_get_room_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.Room.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_room(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_room_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_get_room") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_get_room_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_get_room") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.GetRoomRequest.pb(messaging.GetRoomRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.Room.to_json(messaging.Room()) - req.return_value.content = return_value - - request = messaging.GetRoomRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.Room() - post_with_metadata.return_value = messaging.Room(), metadata - - client.get_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_room_rest_bad_request(request_type=messaging.UpdateRoomRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'room': {'name': 'rooms/sample1'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_room(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.UpdateRoomRequest, - dict, -]) -def test_update_room_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'room': {'name': 'rooms/sample1'}} - request_init["room"] = {'name': 'rooms/sample1', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = messaging.UpdateRoomRequest.meta.fields["room"] - - 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["room"].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["room"][field])): - del request_init["room"][field][i][subfield] - else: - del request_init["room"][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 = messaging.Room( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.Room.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_room(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Room) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_room_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_update_room") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_update_room_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_update_room") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.UpdateRoomRequest.pb(messaging.UpdateRoomRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.Room.to_json(messaging.Room()) - req.return_value.content = return_value - - request = messaging.UpdateRoomRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.Room() - post_with_metadata.return_value = messaging.Room(), metadata - - client.update_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_room_rest_bad_request(request_type=messaging.DeleteRoomRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_room(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.DeleteRoomRequest, - dict, -]) -def test_delete_room_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_room(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_room_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "pre_delete_room") as pre: - pre.assert_not_called() - pb_message = messaging.DeleteRoomRequest.pb(messaging.DeleteRoomRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = messaging.DeleteRoomRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_room(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_list_rooms_rest_bad_request(request_type=messaging.ListRoomsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_rooms(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.ListRoomsRequest, - dict, -]) -def test_list_rooms_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.ListRoomsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.ListRoomsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_rooms(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRoomsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_rooms_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_list_rooms") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_list_rooms_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_list_rooms") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.ListRoomsRequest.pb(messaging.ListRoomsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.ListRoomsResponse.to_json(messaging.ListRoomsResponse()) - req.return_value.content = return_value - - request = messaging.ListRoomsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.ListRoomsResponse() - post_with_metadata.return_value = messaging.ListRoomsResponse(), metadata - - client.list_rooms(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_blurb_rest_bad_request(request_type=messaging.CreateBlurbRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_blurb(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.CreateBlurbRequest, - dict, -]) -def test_create_blurb_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.Blurb( - name='name_value', - user='user_value', - text='text_value', - legacy_room_id='legacy_room_id_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 = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_blurb(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_blurb_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_create_blurb") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_create_blurb_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_create_blurb") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.CreateBlurbRequest.pb(messaging.CreateBlurbRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.Blurb.to_json(messaging.Blurb()) - req.return_value.content = return_value - - request = messaging.CreateBlurbRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.Blurb() - post_with_metadata.return_value = messaging.Blurb(), metadata - - client.create_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_blurb_rest_bad_request(request_type=messaging.GetBlurbRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1/blurbs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_blurb(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.GetBlurbRequest, - dict, -]) -def test_get_blurb_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1/blurbs/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 = messaging.Blurb( - name='name_value', - user='user_value', - text='text_value', - legacy_room_id='legacy_room_id_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 = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_blurb(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_blurb_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_get_blurb") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_get_blurb_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_get_blurb") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.GetBlurbRequest.pb(messaging.GetBlurbRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.Blurb.to_json(messaging.Blurb()) - req.return_value.content = return_value - - request = messaging.GetBlurbRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.Blurb() - post_with_metadata.return_value = messaging.Blurb(), metadata - - client.get_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_blurb_rest_bad_request(request_type=messaging.UpdateBlurbRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'blurb': {'name': 'rooms/sample1/blurbs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_blurb(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.UpdateBlurbRequest, - dict, -]) -def test_update_blurb_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'blurb': {'name': 'rooms/sample1/blurbs/sample2'}} - request_init["blurb"] = {'name': 'rooms/sample1/blurbs/sample2', 'user': 'user_value', 'text': 'text_value', 'image': b'image_blob', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'legacy_room_id': 'legacy_room_id_value', 'legacy_user_id': 'legacy_user_id_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 = messaging.UpdateBlurbRequest.meta.fields["blurb"] - - 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["blurb"].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["blurb"][field])): - del request_init["blurb"][field][i][subfield] - else: - del request_init["blurb"][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 = messaging.Blurb( - name='name_value', - user='user_value', - text='text_value', - legacy_room_id='legacy_room_id_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 = messaging.Blurb.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_blurb(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.Blurb) - assert response.name == 'name_value' - assert response.user == 'user_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_blurb_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_update_blurb") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_update_blurb_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_update_blurb") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.UpdateBlurbRequest.pb(messaging.UpdateBlurbRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.Blurb.to_json(messaging.Blurb()) - req.return_value.content = return_value - - request = messaging.UpdateBlurbRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.Blurb() - post_with_metadata.return_value = messaging.Blurb(), metadata - - client.update_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_blurb_rest_bad_request(request_type=messaging.DeleteBlurbRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1/blurbs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_blurb(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.DeleteBlurbRequest, - dict, -]) -def test_delete_blurb_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1/blurbs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_blurb(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_blurb_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "pre_delete_blurb") as pre: - pre.assert_not_called() - pb_message = messaging.DeleteBlurbRequest.pb(messaging.DeleteBlurbRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = messaging.DeleteBlurbRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_blurb(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_list_blurbs_rest_bad_request(request_type=messaging.ListBlurbsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_blurbs(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.ListBlurbsRequest, - dict, -]) -def test_list_blurbs_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.ListBlurbsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = messaging.ListBlurbsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_blurbs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBlurbsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_blurbs_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_list_blurbs") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_list_blurbs_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_list_blurbs") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.ListBlurbsRequest.pb(messaging.ListBlurbsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.ListBlurbsResponse.to_json(messaging.ListBlurbsResponse()) - req.return_value.content = return_value - - request = messaging.ListBlurbsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.ListBlurbsResponse() - post_with_metadata.return_value = messaging.ListBlurbsResponse(), metadata - - client.list_blurbs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_search_blurbs_rest_bad_request(request_type=messaging.SearchBlurbsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.search_blurbs(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.SearchBlurbsRequest, - dict, -]) -def test_search_blurbs_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_blurbs(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_search_blurbs_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_search_blurbs") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_search_blurbs_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_search_blurbs") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.SearchBlurbsRequest.pb(messaging.SearchBlurbsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = messaging.SearchBlurbsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.search_blurbs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_stream_blurbs_rest_bad_request(request_type=messaging.StreamBlurbsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.stream_blurbs(request) - - -@pytest.mark.parametrize("request_type", [ - messaging.StreamBlurbsRequest, - dict, -]) -def test_stream_blurbs_rest_call_success(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'rooms/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = messaging.StreamBlurbsResponse( - action=messaging.StreamBlurbsResponse.Action.CREATE, - ) - - # 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 = messaging.StreamBlurbsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.stream_blurbs(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, messaging.StreamBlurbsResponse) - assert response.action == messaging.StreamBlurbsResponse.Action.CREATE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stream_blurbs_rest_interceptors(null_interceptor): - transport = transports.MessagingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.MessagingRestInterceptor(), - ) - client = MessagingClient(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.MessagingRestInterceptor, "post_stream_blurbs") as post, \ - mock.patch.object(transports.MessagingRestInterceptor, "post_stream_blurbs_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.MessagingRestInterceptor, "pre_stream_blurbs") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = messaging.StreamBlurbsRequest.pb(messaging.StreamBlurbsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = messaging.StreamBlurbsResponse.to_json(messaging.StreamBlurbsResponse()) - req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) - - request = messaging.StreamBlurbsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = messaging.StreamBlurbsResponse() - post_with_metadata.return_value = messaging.StreamBlurbsResponse(), metadata - - client.stream_blurbs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_send_blurbs_rest_error(): - - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.send_blurbs({}) - assert ( - "Method SendBlurbs is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_connect_rest_error(): - - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.connect({}) - assert ( - "Method Connect is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'users/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'users/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'operations/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_initialize_client_w_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_room_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_room), - '__call__') as call: - client.create_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateRoomRequest() - assert args[0] == request_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_room_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_room), - '__call__') as call: - client.get_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetRoomRequest() - assert args[0] == request_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_room_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_room), - '__call__') as call: - client.update_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateRoomRequest() - assert args[0] == request_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_room_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_room), - '__call__') as call: - client.delete_room(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteRoomRequest() - assert args[0] == request_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_rooms_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_rooms), - '__call__') as call: - client.list_rooms(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListRoomsRequest() - assert args[0] == request_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_blurb_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_blurb), - '__call__') as call: - client.create_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.CreateBlurbRequest() - assert args[0] == request_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_blurb_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_blurb), - '__call__') as call: - client.get_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.GetBlurbRequest() - assert args[0] == request_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_blurb_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_blurb), - '__call__') as call: - client.update_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.UpdateBlurbRequest() - assert args[0] == request_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_blurb_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_blurb), - '__call__') as call: - client.delete_blurb(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.DeleteBlurbRequest() - assert args[0] == request_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_blurbs_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_blurbs), - '__call__') as call: - client.list_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.ListBlurbsRequest() - assert args[0] == request_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_search_blurbs_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_blurbs), - '__call__') as call: - client.search_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.SearchBlurbsRequest() - assert args[0] == request_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_stream_blurbs_empty_call_rest(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stream_blurbs), - '__call__') as call: - client.stream_blurbs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = messaging.StreamBlurbsRequest() - assert args[0] == request_msg - - -def test_messaging_rest_lro_client(): - client = MessagingClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.MessagingGrpcTransport, - ) - -def test_messaging_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.MessagingTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_messaging_base_transport(): - # Instantiate the base transport. - with mock.patch('google.showcase_v1beta1.services.messaging.transports.MessagingTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.MessagingTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_room', - 'get_room', - 'update_room', - 'delete_room', - 'list_rooms', - 'create_blurb', - 'get_blurb', - 'update_blurb', - 'delete_blurb', - 'list_blurbs', - 'search_blurbs', - 'stream_blurbs', - 'send_blurbs', - 'connect', - '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_messaging_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.showcase_v1beta1.services.messaging.transports.MessagingTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MessagingTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_messaging_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.showcase_v1beta1.services.messaging.transports.MessagingTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MessagingTransport() - adc.assert_called_once() - - -def test_messaging_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) - MessagingClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.MessagingGrpcTransport, - transports.MessagingGrpcAsyncIOTransport, - ], -) -def test_messaging_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.MessagingGrpcTransport, - transports.MessagingGrpcAsyncIOTransport, - transports.MessagingRestTransport, - ], -) -def test_messaging_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.MessagingGrpcTransport, grpc_helpers), - (transports.MessagingGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_messaging_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( - "localhost:7469", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="localhost:7469", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.MessagingGrpcTransport, transports.MessagingGrpcAsyncIOTransport]) -def test_messaging_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_messaging_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.MessagingRestTransport ( - 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_messaging_host_no_port(transport_name): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='localhost'), - transport=transport_name, - ) - assert client.transport._host == ( - 'localhost:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://localhost' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_messaging_host_with_port(transport_name): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='localhost:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'localhost:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://localhost:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_messaging_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = MessagingClient( - credentials=creds1, - transport=transport_name, - ) - client2 = MessagingClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_room._session - session2 = client2.transport.create_room._session - assert session1 != session2 - session1 = client1.transport.get_room._session - session2 = client2.transport.get_room._session - assert session1 != session2 - session1 = client1.transport.update_room._session - session2 = client2.transport.update_room._session - assert session1 != session2 - session1 = client1.transport.delete_room._session - session2 = client2.transport.delete_room._session - assert session1 != session2 - session1 = client1.transport.list_rooms._session - session2 = client2.transport.list_rooms._session - assert session1 != session2 - session1 = client1.transport.create_blurb._session - session2 = client2.transport.create_blurb._session - assert session1 != session2 - session1 = client1.transport.get_blurb._session - session2 = client2.transport.get_blurb._session - assert session1 != session2 - session1 = client1.transport.update_blurb._session - session2 = client2.transport.update_blurb._session - assert session1 != session2 - session1 = client1.transport.delete_blurb._session - session2 = client2.transport.delete_blurb._session - assert session1 != session2 - session1 = client1.transport.list_blurbs._session - session2 = client2.transport.list_blurbs._session - assert session1 != session2 - session1 = client1.transport.search_blurbs._session - session2 = client2.transport.search_blurbs._session - assert session1 != session2 - session1 = client1.transport.stream_blurbs._session - session2 = client2.transport.stream_blurbs._session - assert session1 != session2 - session1 = client1.transport.send_blurbs._session - session2 = client2.transport.send_blurbs._session - assert session1 != session2 - session1 = client1.transport.connect._session - session2 = client2.transport.connect._session - assert session1 != session2 -def test_messaging_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.MessagingGrpcTransport( - 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_messaging_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.MessagingGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize("transport_class", [transports.MessagingGrpcTransport, transports.MessagingGrpcAsyncIOTransport]) -def test_messaging_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.MessagingGrpcTransport, transports.MessagingGrpcAsyncIOTransport]) -def test_messaging_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_messaging_grpc_lro_client(): - client = MessagingClient( - 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_messaging_grpc_lro_async_client(): - client = MessagingAsyncClient( - 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_blurb_path(): - user = "squid" - legacy_user = "clam" - blurb = "whelk" - expected = "users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}".format(user=user, legacy_user=legacy_user, blurb=blurb, ) - actual = MessagingClient.blurb_path(user, legacy_user, blurb) - assert expected == actual - - -def test_parse_blurb_path(): - expected = { - "user": "octopus", - "legacy_user": "oyster", - "blurb": "nudibranch", - } - path = MessagingClient.blurb_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_blurb_path(path) - assert expected == actual - -def test_room_path(): - room = "cuttlefish" - expected = "rooms/{room}".format(room=room, ) - actual = MessagingClient.room_path(room) - assert expected == actual - - -def test_parse_room_path(): - expected = { - "room": "mussel", - } - path = MessagingClient.room_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_room_path(path) - assert expected == actual - -def test_user_path(): - user = "winkle" - expected = "users/{user}".format(user=user, ) - actual = MessagingClient.user_path(user) - assert expected == actual - - -def test_parse_user_path(): - expected = { - "user": "nautilus", - } - path = MessagingClient.user_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_user_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = MessagingClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = MessagingClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = MessagingClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = MessagingClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = MessagingClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = MessagingClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = MessagingClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = MessagingClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = MessagingClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = MessagingClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = MessagingClient.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.MessagingTransport, '_prep_wrapped_messages') as prep: - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.MessagingTransport, '_prep_wrapped_messages') as prep: - transport_class = MessagingClient.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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_delete_operation_flattened(): - client = MessagingClient( - 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 - - client.delete_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() - -@pytest.mark.asyncio -async def test_delete_operation_flattened_async(): - client = MessagingAsyncClient( - 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 - ) - await client.delete_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() - - -def test_cancel_operation(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_cancel_operation_flattened(): - client = MessagingClient( - 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 - - client.cancel_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() - -@pytest.mark.asyncio -async def test_cancel_operation_flattened_async(): - client = MessagingAsyncClient( - 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 - ) - await client.cancel_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() - - -def test_get_operation(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_get_operation_flattened(): - client = MessagingClient( - 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() - - client.get_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() - -@pytest.mark.asyncio -async def test_get_operation_flattened_async(): - client = MessagingAsyncClient( - 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() - ) - await client.get_operation() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() - - -def test_list_operations(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_operations_flattened(): - client = MessagingClient( - 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() - - client.list_operations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() - -@pytest.mark.asyncio -async def test_list_operations_flattened_async(): - client = MessagingAsyncClient( - 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() - ) - await client.list_operations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() - - -def test_list_locations(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_list_locations_flattened(): - client = MessagingClient( - 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() - - client.list_locations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() - -@pytest.mark.asyncio -async def test_list_locations_flattened_async(): - client = MessagingAsyncClient( - 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() - ) - await client.list_locations() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() - - -def test_get_location(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_get_location_flattened(): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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() - - client.get_location() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() - -@pytest.mark.asyncio -async def test_get_location_flattened_async(): - client = MessagingAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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() - ) - await client.get_location() - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() - - -def test_set_iam_policy(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_set_iam_policy_flattened(): - client = MessagingClient( - 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() - - client.set_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = MessagingAsyncClient( - 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() - ) - - await client.set_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -def test_get_iam_policy(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_get_iam_policy_flattened(): - client = MessagingClient( - 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() - - client.get_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = MessagingAsyncClient( - 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() - ) - - await client.get_iam_policy() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -def test_test_iam_permissions(transport: str = "grpc"): - client = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = MessagingAsyncClient( - 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 = MessagingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingAsyncClient( - 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_test_iam_permissions_flattened(): - client = MessagingClient( - 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() - - client.test_iam_permissions() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = MessagingAsyncClient( - 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() - ) - - await client.test_iam_permissions() - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_transport_close_grpc(): - client = MessagingClient( - 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 = MessagingAsyncClient( - 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 = MessagingClient( - 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 = MessagingClient( - 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", [ - (MessagingClient, transports.MessagingGrpcTransport), - (MessagingAsyncClient, transports.MessagingGrpcAsyncIOTransport), -]) -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/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index d56fed3e20f7..9d3d9fefaa8d 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -36,6 +36,18 @@ showcase_version = os.environ.get("SHOWCASE_VERSION", "0.35.0") ADS_TEMPLATES = path.join(path.dirname(__file__), "gapic", "ads-templates") +CURRENT_DIRECTORY = Path(__file__).parent.absolute() +# Path to the centralized mypy configuration file at the repository root. +# Search upwards to support running nox from both monorepo packages and integration test goldens. +MYPY_CONFIG_FILE = next( + ( + str(p / "mypy.ini") + for p in CURRENT_DIRECTORY.parents + if (p / "mypy.ini").exists() + ), + str(CURRENT_DIRECTORY.parent.parent / "mypy.ini"), +) + RUFF_VERSION = "ruff==0.14.14" LINT_PATHS = ["docs", "gapic", "tests", "test_utils", "noxfile.py", "setup.py"] # Ruff uses globs for excludes (different from Black's regex) @@ -350,7 +362,6 @@ def showcase_library( ) # Install the generated showcase library. - session.install("-e", "../google-api-core") if templates == "DEFAULT": # Use the constraints file for the specific python runtime version. # We do this to make sure that we're testing against the lowest @@ -381,9 +392,6 @@ def showcase_library( # Install the library without a constraints file. session.install("-e", tmp_dir) - import shutil - shutil.rmtree("generated_showcase", ignore_errors=True) - shutil.copytree(tmp_dir, "generated_showcase") yield tmp_dir @@ -508,10 +516,6 @@ def run_showcase_unit_tests(session, fail_under=100, rest_async_io_enabled=False session.run("python", "-m", "pip", "freeze") # Run the tests. - import os - env = os.environ.copy() - env["GOOGLE_API_USE_CLIENT_CERTIFICATE"] = "false" - env["CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE"] = "" session.run( "py.test", *( @@ -525,7 +529,6 @@ def run_showcase_unit_tests(session, fail_under=100, rest_async_io_enabled=False path.join("tests", "unit"), ] ), - env=env, ) @@ -739,7 +742,7 @@ def mypy(session): "click==8.1.3", ) session.install(".") - session.run("mypy", "-p", "gapic") + session.run("mypy", f"--config-file={MYPY_CONFIG_FILE}", "-p", "gapic") @nox.session(python=NEWEST_PYTHON) @@ -751,7 +754,7 @@ def lint(session): """ # TODO(https://github.com/googleapis/google-cloud-python/issues/16186): - # SKIP: This session was not enforced in the standalone (split) repo + # SKIP: This session was not enforced in the standalone (split) repo # and is disabled here to ensure a "move-only" migration. session.skip( "Linting was not enforced in the split repo. " @@ -781,9 +784,11 @@ def lint(session): @nox.session(python=NEWEST_PYTHON) def lint_setup_py(session): # TODO(https://github.com/googleapis/google-cloud-python/issues/16186): - # SKIP: This session was not enforced in the standalone (split) repo + # SKIP: This session was not enforced in the standalone (split) repo # and is disabled here to ensure a "move-only" migration. - session.skip("Skipping now to avoid changing code during migration. See Issue #16186") + session.skip( + "Skipping now to avoid changing code during migration. See Issue #16186" + ) @nox.session(python="3.10") @@ -858,9 +863,11 @@ def prerelease_deps(session, protobuf_implementation): """ Run all tests with pre-release versions of dependencies installed. """ - # TODO(https://github.com/googleapis/google-cloud-python/issues/16184): + # TODO(https://github.com/googleapis/google-cloud-python/issues/16184): # Implement pre-release dependency logic to test against upcoming runtime changes. - session.skip("prerelease_deps session is not yet implemented for gapic-generator-python.") + session.skip( + "prerelease_deps session is not yet implemented for gapic-generator-python." + ) @nox.session(python=NEWEST_PYTHON) @@ -870,6 +877,8 @@ def prerelease_deps(session, protobuf_implementation): ) def core_deps_from_source(session, protobuf_implementation): """Run all tests with core dependencies installed from source.""" - # TODO(https://github.com/googleapis/google-cloud-python/issues/16185): + # TODO(https://github.com/googleapis/google-cloud-python/issues/16185): # Implement logic to install core packages directly from the mono-repo directories. - session.skip("core_deps_from_source session is not yet implemented for gapic-generator-python.") \ No newline at end of file + session.skip( + "core_deps_from_source session is not yet implemented for gapic-generator-python." + ) From 0b3d65c0cb0f1114bf58889021c7117dcdff4253 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 21 Jul 2026 23:47:15 +0000 Subject: [PATCH 5/5] fix(generator): install local google-api-core in nox test sessions --- packages/gapic-generator/api-common-protos | 1 - packages/gapic-generator/noxfile.py | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) delete mode 160000 packages/gapic-generator/api-common-protos diff --git a/packages/gapic-generator/api-common-protos b/packages/gapic-generator/api-common-protos deleted file mode 160000 index 3332dec52775..000000000000 --- a/packages/gapic-generator/api-common-protos +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3332dec527759859840a3a2ff108c67a54708130 diff --git a/packages/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index 9d3d9fefaa8d..d19c9a895a9a 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -193,6 +193,7 @@ def fragment(session, use_ads_templates=False): "grpcio-tools", ) session.install("-e", ".") + session.install("-e", "../google-api-core") # The specific failure is `Plugin output is unparseable` if session.python == "3.10": @@ -257,6 +258,7 @@ def showcase_library( # Install gapic-generator-python session.install("-e", ".") + session.install("-e", "../google-api-core") # Install grpcio-tools for protoc session.install("grpcio-tools")